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.
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.
Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().
You can use Enumerable.Where and it will return all the matching elements collection.
var res = persons.Where(c=>c.AttributeName == 23);
If you want to ensure you have only match you can use single.
var res = persons.Single(c=>c.AttributeName == 23);
Single Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With