开发者

Linq Expressions and Aggregate classes

开发者 https://www.devze.com 2023-01-16 11:40 出处:网络
How do I build Linq Expressions for aggregate classes? Let me explain with an example of what I am trying to do. Say, I want to find all employees with pay not equal to 50000 and here\'s the class str

How do I build Linq Expressions for aggregate classes? Let me explain with an example of what I am trying to do. Say, I want to find all employees with pay not equal to 50000 and here's the class structure.

    Employee e1 = new Employee { Name = "Jane", PDetail = new PayDetail { Salary = 100000 } };
    Employee e2 = new Employee { Name = "Joe", PDetail = new PayDetail { Salary = 50000 } };

    e开发者_如何学Cmps.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());

EDIT: Any help with the null issue (as noted in the comments)? Thanks


You're not passing the correct arguments to the Enumerable.Where method. You are passing a list of Employee and a method that works on PayDetail. You could use

var query = Enumerable
    .Where(emps.Select(e => e.PDetail), (Func<PayDetail, Boolean>)pred.Compile());

or the shorter version

var query = emps.Select(e => e.PDetail)
    .Where((Func<PayDetail, Boolean>)pred.Compile());

Which will get you the right PayDetails but not the right Employees'. I believe you're really looking for:

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());
0

精彩评论

暂无评论...
验证码 换一张
取 消