"Or" equivalent in Linq Where() lambda expression

dstr picture dstr · Jan 20, 2010 · Viewed 86.8k times · Source

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

Answer

tvanfosson picture tvanfosson · Jan 20, 2010

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