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