I have list of type Person which has 3 properties Id, Name, Age
var per1 = new Person((1, "John", 33);
var per2 = new Person((2, "Anna", 23);
var persons = new List<Person>();
persons.Add(per1);
persons.Add(per2);
using linq I want to select person which age matched with my input, for example 33.
I know how to use any but I dont know how to select object which matches with my condition.
For one match:
var match = persons.Single(p => your condition);
For many matches, use persons.Where(condition)
. There are also many variants of picking just one person, such as FirstOrDefault
, First
, Last
, LastOrDefault
, and SingleOrDefault
. Each has slightly different semantics depending on what exactly you want.