views:

4316

answers:

3

What is the best way to assemble a dynamic WHERE clause to a LINQ statement?

I have several dozen checkboxes on a form and am passing them back as: Dictionary<string, List<string>> (Dictionary<fieldName,List<values>>) to my LINQ query.

public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictionary)
{
    var q = from c in db.ProductDetail
            where c.ProductGroupName == productGroupName && c.ProductTypeName == productTypeName
            // insert dynamic filter here
            orderby c.ProductTypeName
            select c;
    return q;
}

Any help is appreciated!

+6  A: 
Thomas Stock
+1  A: 

I had same question ( http://stackoverflow.com/questions/798553/user-defined-filter-for-linq ), and @tvanfosson told me about Dynamic Linq ( http://code.msdn.microsoft.com/csharpsamples ).

TcKs
+3  A: 

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Linus