tags:

views:

1144

answers:

6

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

+5  A: 

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

MyDataSource.Where(data => data.a == 'a' || data.a == 'b')
Simon Steele
+1  A: 

One solution might be Dynamic Linq:

(http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)

Randy Minder
+2  A: 

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

var something = from s in mycollection
                where s.something == 32 || 
                      s.somethingelse == 45 
                select s
Muad'Dib
+9  A: 

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 );
tvanfosson
Nice use of the predicates! +1 :)
Alastair Pitts
A: 
var query = ObjectTypes.Where(s => s.a == 1 || s.a == 2)
Yaakov Ellis
A: 

in your .Where() call use the standard Boolean 'Or' operator, ||.

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

All the Where call does is a Boolean comparison on anything you want, so you can fill it with as much conditional logic as you wish.

Alastair Pitts