自定义lambda表达式不能按预期工作

时间:2017-05-15 14:46:10

标签: c# linq lambda

我正在制作一个像这样的lambda表达式:

var property = typeof(Customer).GetProperty(inputArray[0], BindingFlags.Instance | BindingFlags.Public);
var parameter = Expression.Parameter(typeof(Customer));
var memberExpression = Expression.Property(parameter, property);
var eq = Expression.Equal(memberExpression, Expression.Constant(value));
//Combining eq with ANDs and ORs
var lambdaExpression = Expression.Lambda<Func<Customer, bool>>(eq, parameter);
// the lambda expression looks like this : {Param_0 => ((Param_0.NAME== "JASON") And (Param_0.NAME == "JASON"))}

var filteredCustomers = db.Customer.Where(lambdaExpression);
var list = filteredCustomers.ToList(); 

我可以看到db中有名称为JASON的记录。但是列表计数始终为零。你能告诉我这是什么问题吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

对于看过这篇文章的未来访问者,OP已经删除了额外空格的值。

var param = Expression.Parameter(typeof(Customer), "p");
var memberExpression = Expression.PropertyOrField(param, "Your_Property_Name");
var body = Expression.Equal(memberExpression, Expression.Constant(value.Trim()));
var lambda = Expression.Lambda(body, param);