Petr Had
Petr Had

Reputation: 147

Use Func in Ilist, why lambda expression?

I have a IList of Client type. I would need to iterate through it and return an element that matches some condition. I wanted to use "smarter" way than foreach so I tried Single method, however I am not sure why this works and if it can be done different way (I am not that advanced):

private client GetClientByID(short ID)
{
   return this.ListOfClient.Single(c => c.ID == ID);
}

I do not understand the use of lambda expression..I tried an anonymous method but was not able to write it properly.. thanks

Upvotes: 2

Views: 709

Answers (2)

Alex Kovanev
Alex Kovanev

Reputation: 1888

From MSDN

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

That means your code is equivalent to

private client GetClientByID(short ID)
{
   return this.ListOfClient.Single(delegate(Client c) { return c.ID == ID; });
}

Single is a linq extension method that could be determined as Enumerable.Single Method (IEnumerable, Func) Pay attention at the second parameter

Func<TSource, bool> predicate

From another article of MSDN

Predicate Delegate. Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

That means it will check the criteria return c.ID == ID; for each element of the collection and return the one that answers the requirements.

PS Be careful about Single method. I'd prefer to use SingleOrDefault or FirstOrDefault depending on the task.

Upvotes: 0

Sebastian Piu
Sebastian Piu

Reputation: 8008

Your code is correct, this lambda expression is basically a method that returns bool (in this specific case). So imagine that for every item in your ListOfClient it will try to execute that method, if it returns true, then it will return the item.

You need to be carefull that by using Single it will fail if there are 0 or more than 1 matches in your List.

If you are sure that there will be only 1 item then it is fine, if not you can use one of the following:

  • List.SingleOrDefault() //returns null if there are 0 items, fails if there are more than 1
  • List.First() //fails if there are 0 items
  • List.FirstOrDefault() //never fails, returns null if there are 0 items

Upvotes: 1

Related Questions