views:

82

answers:

2
IQueryable<SomeType> result = (from x in Context.XXX select x);

now what I need to do is the following (written pseudo code, I need actual code):

foreach(var i in items)
{
  // Where the object "i" has 2 properties
  // 1) i.Operator (values of which can be AND or OR)
  // 2) i.SomeID (values of which can be 1 .. 10)

  // I need to build the LINQ query with "ands" and "ors" based on the i's in this foreach
}
+1  A: 

The naive approach would be to chain calls to the Where method, but that way you can only achieve the AND behavior

Check out the PredicateBuilder class by Joseph Albahari. It allows to build dynamic Linq queries with the OR operator

Thomas Levesque
A: 

We use the Dynamic LINQ library to accomplish exactly what you're trying to do (found here: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)

You can use something like:

var finalResults = results.Where("Your where clause");

where "Your where clause" is the string containing your dynamically-generated where clause.

Keith