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.

Leave a Comment