Linq GroupBy和多列

时间:2010-12-14 12:52:44

标签: c# linq group-by linq-to-objects

class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}


List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}

原谅相当人为的例子。

如何在GetEmployeeExpenses中获得员工团队?我假设我需要第二组,但我无法解决语法问题。

请注意,对于给定的员工,他们的Team始终是相同的,所以我很乐意将Team作为第一个按记录分组的。{/ p>

所以...

ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }

2 个答案:

答案 0 :(得分:9)

在您的特定情况下,您可以在Select中使用x.First().Team来获取您的团队信息。

对于实际需要在多个字段上进行分组的其他情况,您可以对匿名类型进行分组。如

someQuery.GroupBy(f => new { f.Foo, f.Bar }).Select(...);

答案 1 :(得分:0)

查询它的表达式版本(可能更容易阅读,具体取决于情况和分组数量):

IEnumerable<EmployeeExpense> GetEmployeeExpenses(List<ExpenseClaim> claims)
{
    return 
        from c in claims
        group c by c.EmployeeId into groupedById
        from g in groupedById
        group g by g.Team into groupedByTeam
        let firstElement = groupedByTeam.First()
        select new EmployeeExpense {
            EmployeeId = firstElement.EmployeeId,
            Team = firstElement.Team,
            Cost = groupedByTeam.Sum(e => e.Cost)
        };
}