如何使用linq通过多个列进行分组

时间:2017-06-22 16:05:51

标签: linq

如何按来自不同表格的多个列进行分组,最后总结金额列

__call__()

这是我尝试过的

      var result = _employeeDAL.GetList(db =>
                        from es in db.Set<EmployeeSchedule>()
                        join est in db.Set<EmployeeSalaryType>() on est.Employee_Id equals es.Employee_Id
                        join et in db.Set<EmployeeType>() on est.Employee_Salary_Id equals et.Employee_Salary_Id
                        where es.Status == "JOINED" && es.JoinedDate.Year == 2017
                        select new
                        {
                            EmployeeName = es.EmployeeName
                           ,Amount = est.Amount ///----------> SUM THIS
                           ,EmployeeType = et.EmployeeType
                        });

1 个答案:

答案 0 :(得分:2)

你快到了。只需要考虑在group ... by ... into grp子句之后,范围中唯一的变量是grp

所以在where之前移动group by子句并在grp.Key中使用select

var result = _employeeDAL.GetList(db =>
    from es in db.Set<EmployeeSchedule>()
    join est in db.Set<EmployeeSalaryType>() on est.Employee_Id equals es.Employee_Id
    join et in db.Set<EmployeeType>() on est.Employee_Salary_Id equals et.Employee_Salary_Id
    where es.Status == "JOINED" && es.JoinedDate.Year == 2017
    group new { es, est, et } by new { es.EmployeeName, et.EmployeeType } into grp
    select new
    {
        EmployeeName = grp.Key.EmployeeName,
        Amount = grp.Sum(g => g.est.Amount),
        EmployeeType = grp.Key.EmployeeType,
    });