Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Contains Based on Property

Tags:

.net

linq

Need to check if a list contains an item with a property value of X.

Been using FirstOrDefault and comparing to null:

   searchItems.FirstOrDefault(si => si.ID == 99) == null

Is there better way to do this?

I cannot get past syntax errors on Contains. Thanks.

like image 960
paparazzo Avatar asked Mar 02 '12 15:03

paparazzo


People also ask

How Contains work in LINQ?

LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

How do I add and condition in LINQ query?

If you do not call ToList() and your final mapping to the DTO type, you can add Where clauses as you go, and build the results at the end: var query = from u in DataContext. Users where u. Division == strUserDiv && u.

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 the Any method

searchItems.Any(si => si.ID == 99)
like image 69
Aducci Avatar answered Oct 05 '22 23:10

Aducci


There are probably a few ways to do this, here's another one:

bool any = searchItems.Any(si => si.ID == 99);
like image 41
Christoffer Avatar answered Oct 06 '22 00:10

Christoffer