panjo panjo - 1 year ago 77
C# Question

select object which matches with my condition using linq

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download