Storm
Storm

Reputation: 4475

How to write a LINQ query to do this

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
}

Upvotes: 0

Views: 141

Answers (2)

Keith
Keith

Reputation: 5391

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.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292695

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

Upvotes: 1

Related Questions