Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select object which matches with my condition using linq

Tags:

c#

.net

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

like image 648
panjo Avatar asked Jul 18 '13 11:07

panjo


People also ask

How do I write a selection in LINQ?

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.

What a LINQ query returns in LINQ to object?

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.

How do I return a single value from a list using LINQ?

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


2 Answers

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.

like image 177
Adil Avatar answered Sep 28 '22 00:09

Adil


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.

like image 24
ChaseMedallion Avatar answered Sep 27 '22 23:09

ChaseMedallion