Linq: "Or" equivalent to Where ()

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

+72
linq where-clause
Jan 20 '10 at 13:16
source share
5 answers

You can do this as part of the Where clause (extension method). If you need to build a complex query dynamically, you can use PredicateBuilder .

var query = collection.Where( c => cA == 1 || cB == 2 ); 

Or using PredicateBuilder

  var predicate = PredicateBuilder.False<Foo>(); predicate = predicate.Or( f => fA == 1 ); if (allowB) { predicate = predicate.Or( f => fB == 1 ); } var query = collection.Where( predicate ); 
+151
Jan 20 '10 at 13:19
source share

You can use the standard .NET Boolean operators in your one place where:

 MyDataSource.Where(data => data.a == 'a' || data.a == 'b') 
+20
Jan 20 '10 at 13:18
source share

You use all the same operators as in regular C # ===> || for "or" && for "and" etc.

 var something = from s in mycollection where s.something == 32 || s.somethingelse == 45 select s 
+15
Jan 20 '10 at 13:19
source share
+3
Jan 20 '10 at 13:18
source share

in your .Where() call use the standard boolean operator "Or", || .

 var query = items.Where(item => (item == 1 || item == 2)); 

All that takes place is a logical comparison on everything you want so that you can fill it with as much conditional logic as possible.

+1
Jan 20 '10 at 13:21
source share



All Articles