从this link起,我可以动态创建一个表达式
此代码可以动态创建s => s.Id == 1
ParameterExpression argParam = Expression.Parameter(typeof(User), "s");
var propertyExp = Expression.Property(parameterExp, "Id");
var constExp = Expression.Constant(1);
var body = Expression.Equal(propertyExp, constExp);
var lambda = Expression.Lambda<Func<User, bool>>(body, parameterExp);
但是我如何创建表达式
如何动态创建:(a,b)=> a.Id == 1 && b.Name ==“名称”
答案 0 :(得分:2)
Func<T, bool>
和Func<T1, T2, bool>
之间的区别在于,第二个接受两个参数,因此您需要使用Expression.Parameter
创建两个参数。
下面的代码将创建一个表达式
(t1,t2)=> t1.Id == 1 && t2.Name ==名称;
private static Expression<Func<T1, T2, bool>> CreateExpression<T1, T2>()
{
var t1 = Expression.Parameter(typeof(T1), "t1");
var t2 = Expression.Parameter(typeof(T2), "t2");
var idProp = Expression.PropertyOrField(t1, "Id");
var nameProp = Expression.PropertyOrField(t2, "Name");
var body = Expression.AndAlso(
Expression.Equal(idProp, Expression.Constant(1)),
Expression.Equal(nameProp, Expression.Constant("name"))
);
var lambda = Expression.Lambda<Func<T1, T2, bool>>(body, t1, t2);
return lambda;
}