如何为聚合类构建Linq表达式?让我解释一下我想要做的事情。说,我想找到薪水不等于50000的所有员工,这里是班级结构。
Employee e1 = new Employee { Name = "Jane", PDetail = new PayDetail { Salary = 100000 } };
Employee e2 = new Employee { Name = "Joe", PDetail = new PayDetail { Salary = 50000 } };
emps.Add(e1);
emps.Add(e2);
//I started doing it this way and this code DOES NOT compile
var parameter = Expression.Parameter(typeof(PayDetail));
var where = Expression.NotEqual(Expression.Property(parameter, "Salary"), Expression.Constant(50000));
var pred = Expression.Lambda(where, parameter);
var query = Enumerable.Where(emps, (Func<PayDetail, Boolean>)pred.Compile());
编辑:有关null问题的任何帮助(如评论中所述)?感谢
答案 0 :(得分:0)
您没有将正确的参数传递给Enumerable.Where
方法。您正在传递Employee
列表以及适用于PayDetail
的方法。你可以用
var query = Enumerable
.Where(emps.Select(e => e.PDetail), (Func<PayDetail, Boolean>)pred.Compile());
或更短的版本
var query = emps.Select(e => e.PDetail)
.Where((Func<PayDetail, Boolean>)pred.Compile());
哪个会为您提供正确的PayDetails
,而不是正确的Employee
s'。我相信你真的在寻找:
var parameter = Expression.Parameter(typeof(Employee));
var where = Expression.NotEqual(Expression.Property(
Expression.Property(parameter, "PDetail"), "Salary"),
Expression.Constant(50000));
var pred = Expression.Lambda(where, parameter);
var query = emps.Where((Func<Employee, Boolean>)pred.Compile());