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);
现在我如何将这个lambada添加到IQuerybale的实例,让我们说_query
_query.Where(lambada.Compile());
答案 0 :(得分:3)
我认为您只需要更改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);
现在它是Expression<Func<Product, bool>>
,IQueryable.Where
将其作为参数。 Expression.Lambda<TDelegate>
返回的TDelegate
也是LambdaExpression
,这就是Expression.Lambda
行在您的情况下编译的原因,在我的情况下,IQueryable.Where
希望将其视为Expression<Func<Product, bool>>
List< Product > products = new List< Product >
{
new Product { Name = "bar" },
new Product { Name = "foo" }
};
IQueryable< Product > queryable = products.AsQueryable().Where( lambda );
。
类似的东西:
{{1}}
答案 1 :(得分:0)
不要使用.Compile
,它会将表达式转换为委托。使用表达式过滤IQueryable
,而不是委托:
_query = _query.Where(lambada);