Dynamically generate LINQ queries Dynamically generate LINQ queries xml xml

Dynamically generate LINQ queries


Here is a solution with expression trees:

var param = Expression.Parameter(typeof(SomeObject), "p");var exp = Expression.Lambda<Func<SomeObject, bool>>(    Expression.Equal(        Expression.Property(param, "Name"),        Expression.Constant("Bob")    ),    param);var query = someObj.Where(exp);

I know it's much more complex, but this may be useful in times.


It's hard for me to tell based on your question, but in some cases you don't need dynamic Linq and can simply do this...

var result = from o in someObj              where (Name == null || o.Name == Name)             && (City == null || o.City == City)             && (State == null || o.State == State)             select o;

This will essentially prevent the data from being filtered when the parameter in question is null. And it still performs well thanks to the short-circuiting behavior in C#.


You'll most certainly want to take a look at Dynamic Linq which will allow you to define the query conditions as text.

As for adding conditions dynamically, you can add conditions to a query using similar syntax to;

if(CategoryIsImportant)    myQuery = myQuery.Where("CategoryId=2");

all of which you can (fairly easily) encode into an XML format of your choice.