Adding LambaExpression to an IQueryable Instance

 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 to add this lambada to an IQuerybale instance, say _query

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

+3
source share
2 answers

I think you just need to change the type 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 Expression<Func<Product, bool>>and IQueryable.Wheretakes it as an argument. Expression.Lambda<TDelegate>returns a TDelegate, which is also LambdaExpression, therefore compiling Expression.Lambdain your case and in my case, but IQueryable.Wherewants to see it as Expression<Func<Product, bool>>.

Sort of:

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

Do not use .Compile, it will convert the expression to a delegate. IQueryablefiltered by expression, not delegate:

_query = _query.Where(lambada);
0
source

Source: https://habr.com/ru/post/1737293/


All Articles