Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic WHERE clause in LINQ

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; } 
like image 938
Keith Barrows Avatar asked May 11 '09 14:05

Keith Barrows


People also ask

What is Dynamic LINQ?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

Is Dynamic LINQ safe?

And Dynamic Linq is actually composed from strings, therefore it is potentially prone to attack by injection. Obviously, the attacker will have to be aware of the fact that you are using DynamicLinq and could attack only preparing the data so it results in valid malicious Dynamic Linq query.

What is predicate in LINQ?

A predicate, or more precisely a predicate functor, is a Boolean-valued function. It is often a unary function, checking one argument against a condition and returning the result. Disregarding functions depending on side effects, there are two nullary functions (without arguments). public static class Predicate.


1 Answers

alt text
(source: scottgu.com)

You need something like this? Use the Linq Dynamic Query Library (download includes examples).

Check out ScottGu's blog for more examples.

like image 199
Thomas Stock Avatar answered Oct 06 '22 01:10

Thomas Stock