Select an object that matches my condition using linq

I have a list of Person types that have 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 a person whose age is the same as my input, for example 33.

I know how to use any, but I don’t know how to choose an object that matches my condition.

+4
source share
3 answers

For one match:

 var match = persons.Single(p => your condition); 

For many matches, use persons.Where(condition) . There are also many choices for just one person, such as FirstOrDefault, First, Last, LastOrDefault and SingleOrDefault. Each of them has slightly different semantics depending on what exactly you want.

+8
source

You can use Enumerable.Where and it will return all collections of matching elements.

 var res = persons.Where(c=>c.AttributeName == 23); 

If you want to make sure that you have only a match, you can use single.

 var res = persons.Single(c=>c.AttributeName == 23); 

Single Returns a single element of a sequence and throws an exception if the sequence does not contain exactly one element.

+3
source

It is very simple.

 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); var sirec = persons.Select(x => x.age = 33); 

Try it and let me know

Note. If this is a single value, use "Single" instead of "Select"

+1
source

Source: https://habr.com/ru/post/1492074/


All Articles