Dynamically generate LINQ queries

We have an object

public class SomeObject
{
   public Name {get;set;}
   public City {get;set;}
   public State {get;set}
   //various other parameters.  Let's say there's ~20
}

Is it possible to dynamically create new LINQ queries without recompilation of source code? Instead, the query parameters come from an XML structure that is stored and updated in the database.

var result = from i in someObj
             where 
             //XML requests Name = 'Bob'...so append this where clause
             name = 'Bob'

Can this be done?


Solution 1:

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.

Solution 2:

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#.

Solution 3:

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.