Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Or" equivalent in Linq Where() lambda expression

Is there a method in Linq where you can use to build SQL strings like "...where (a=1) OR (a=2)"?

like image 361
dstr Avatar asked Jan 20 '10 13:01

dstr


People also ask

What does => mean in LINQ?

The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.

Can you use lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

What is lambda expression in LINQ?

Advertisements. 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 difference between LINQ and lambda expression?

Language Integrated Query (LINQ) is feature of Visual Studio that gives you the capabilities yo query on the language syntax of C#, so you will get SQL kind of queries. And Lambda expression is an anonymous function and is more of a like delegate type.


2 Answers

You can certainly do it within a Where clause (extension method). If you need to build a complex query dynamically, though, you can use a PredicateBuilder.

 var query = collection.Where( c => c.A == 1 || c.B == 2 ); 

Or using a PredicateBuilder

 var predicate = PredicateBuilder.False<Foo>();  predicate = predicate.Or( f => f.A == 1 );  if (allowB)  {     predicate = predicate.Or( f => f.B == 1 );  }   var query = collection.Where( predicate ); 
like image 198
tvanfosson Avatar answered Sep 18 '22 02:09

tvanfosson


You can use the standard .NET boolean operators in your single where clause:

MyDataSource.Where(data => data.a == 'a' || data.a == 'b') 
like image 45
Simon Steele Avatar answered Sep 19 '22 02:09

Simon Steele