Linq GroupBy and multiple columns
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)
);
}开发者_运维百科
Excuse the rather contrived example.
How do I get the employee team in GetEmployeeExpenses
? I'm assuming I need a second group by but I can't work out the syntax.
Note that for a given employee, their Team
will always be the same anyway, so I'd be happy to take the Team
of for example the first grouped by record.
so...
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }
=>
EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }
In your particular case, you could use x.First().Team
inside your Select to get your team information.
For other cases of actually needing to group on multiple fields, you could group on an anonymous type. Such as
someQuery.GroupBy(f => new { f.Foo, f.Bar }).Select(...);
Query expression version of it (might be easier to read, depending on situation and amount of grouping):
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)
};
}
精彩评论