Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: "contains" and a Lambda query

I have a List<BuildingStatus> called buildingStatus. I'd like to check whether it contains a status whose char code (returned by GetCharCode()) equals some variable, v.Status.

Is there some way of doing this, along the lines of the (non-compiling) code below?

buildingStatus.Contains(item => item.GetCharValue() == v.Status) 
like image 257
mark smith Avatar asked Oct 14 '09 14:10

mark smith


People also ask

How to use contains in LINQ query?

All, Any & Contains are quantifier operators in LINQ. All checks if all the elements in a sequence satisfies the specified condition. Any check if any of the elements in a sequence satisfies the specified condition. Contains operator checks whether specified element exists in the collection or not.

Is LINQ lambda function?

The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.

What is lambda operator in C#?

Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don't need to specify the type of the value that you input thus making it more flexible to use. The '=>' is the lambda operator which is used in all lambda expressions.


2 Answers

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status) 
like image 125
Rex M Avatar answered Sep 23 '22 13:09

Rex M


The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status) 
like image 37
flq Avatar answered Sep 23 '22 13:09

flq