动态 Linq/Lambda 过滤
本文关键字:过滤 Lambda Linq 动态 | 更新日期: 2023-09-27 17:56:07
我有一个返回表达式的方法,用于根据客户需求动态过滤记录,我这样做有问题,我想要这样的东西
public Expression<T> FilterCreator<T>(FilterCondition condition, string columnName, object value)
{
Expression<Func<Customer, bool>> query;
// FilterCondition is an enum flag for conditions
if(condition.Condition == ConditionFlags.EQUALS)
{
// here is the problem,
// i want the emailAddress to be dynamic based on the passed columName parameter of the client
// and be able to cast its type of the value that was passed
query = p => p.EmailAddress == (typeof(p.EmailAddress))value;
//i want something like this
// query = p => p.(columnName)=> (typeOf(p.(columnName)))value;
}
else if(condition.Condition == ConditionFlags.CONTAINS)
{
.....
}
return query;
}
有什么建议吗? 提前感谢
你需要构建一个表达式树:
var param = Expression.Parameter<Customer>();
p = Expression.LambdaFunc<Customer, bool>(
Expression.Call(typeof(object), "Equals", null, //non-generic
Expression.Property(param, columnName),
Expresssion.Constant(value)
)
);