Linq: Dynamically Combining Where Clauses with an “OR”

By | 2009-02-18

Using LINQ in C# .Net 3.5, I have often had cases where I wanted to build my predicates dynamically based on the value of different runtime conditions or by iterating through a list, etc.

You can easily append where clauses to an IQueryable<T> like so:

query = query.Where(u => u.Name == “Scott”);
query = query.Where(u => u.City == “Orem”);

But the behavior of this is to “and” all the clauses together. There are often times when you want to dynamically “or” these together. To get all users with the name “Scott” or “Steve.” I stumbled across this article which creates a brilliant class called PredicateBuilder to accomplish this. (It’s just a few lines of code and they are all on the page.)

Using the PredicateBuilder class you can say:

var predicate = PredicateBuider.False<User>();
predicate = predicate.Or(u => u.Name == “Scott”);
predicate = predicate.Or(u => u.Name == “Steve”);

Then just tack that onto your query and you’re golden:

query.Where(predicate);

Leave a Reply

Your email address will not be published. Required fields are marked *