1

I have a method which looks the following way:

bool GetIdByName(string name, out ID id)

I would like to use it inside a lambda expression, to get several 'ids' by a number of 'names':

var ids = names.Select(name => idService.GetIdByName(name, out id));

In this case I will find all the bool values inside my 'ids' variable, which is not what I want. Is it also possible to get the out parameter 'id' of each call into it?

2
  • 1
    Why are you using an out parameter for id? Why not simply return the id itself? Are there cases when no id exists? Commented Aug 24, 2015 at 9:31
  • The existing method which gives back the id was not written by me and I don't want to touch it. Yes there are cases where no id exists. Commented Aug 24, 2015 at 9:44

3 Answers 3

5

You can use a delegate with body for this:

IEnumerable<ID> ids = names.Select
(
    name =>
    {
        ID id;
        GetName(name, out id);

        return id;
    }
);
Sign up to request clarification or add additional context in comments.

Comments

2

I would factor the call to GetIdByName into a method, so that it becomes more composable.

var ids = names.Select(GetId);

private static ID GetId(string name)
{
    ID id;
    idService.GetIdByName(name, out id);
    return id;
}

Comments

2

Are looking for something like that?

var ids = names
  .Select(name => {
    ID id = null; 

    if (!idService.GetIdByName(name, out id))
      id = null; // name doesn't corresponds to any ID

    return id;
  })
  .Where(id => id != null);

In case ID is a struct (and so not nullable):

  var ids = names
    .Select(name => {
      ID id = null; 
      Boolean found = idService.GetIdByName(name, out id);

      return new {
        Found = found,
        ID = id
      };
    })
    .Where(data => data.Found)
    .Select(data => data.id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.