tags:

views:

69

answers:

2
 ParameterExpression parameter = Expression.Parameter(typeof(Product), "x");
        MemberExpression Left = Expression.MakeMemberAccess(parameter, typeof(Product).GetProperty("Name"));
        ConstantExpression Right = Expression.Constant(value, typeof(String));
        BinaryExpression expression = Expression.Equal(Left, Right);
        LambdaExpression lambada = Expression.Lambda<Func<Product, bool>>(expression, parameter);

Now how do I add this lambada to an instance of an IQuerybale, lets say _query

_query.Where(lambada.Compile());?

A: 

Don't use .Compile, it would transform the expression into a delegate. An IQueryable is filtered using an expression, not a delegate :

_query = _query.Where(lambada);
Thomas Levesque
A: 

I think you just need to change the type of lambda

ParameterExpression parameter = Expression.Parameter(typeof(Product), "x");
MemberExpression Left = Expression.MakeMemberAccess(parameter, typeof(Product).GetProperty("Name"));
ConstantExpression Right = Expression.Constant(value, typeof(String));
BinaryExpression expression = Expression.Equal(Left, Right);
Expression< Func< Product, bool > > lambda = Expression.Lambda<Func<Product, bool>>(expression, parameter);

Now it is an Expression<Func<Product, bool>> and IQueryable.Where takes that as an argument. Expression.Lambda<TDelegate> returns a TDelegate that is also a LambdaExpression which is why Expression.Lambda line compiles in your case and in my case, but IQueryable.Where wants to see it as an Expression<Func<Product, bool>>.

Something like:

List< Product > products = new List< Product >
{
    new Product { Name = "bar" }, 
    new Product { Name = "foo" }
};
IQueryable< Product > queryable = products.AsQueryable().Where( lambda );
Mike Two