Christoph Brückmann
Christoph Brückmann

Reputation: 1373

How to use a method with an out parameter in a lambda expression

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?

Upvotes: 1

Views: 71

Answers (3)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

You can use a delegate with body for this:

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

        return id;
    }
);

Upvotes: 5

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

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);

Upvotes: 2

dcastro
dcastro

Reputation: 68710

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;
}

Upvotes: 2

Related Questions