LINQ Interview Question #61
How do you group by multiple fields in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
Use a composite key, commonly an anonymous type, as the GroupBy key. Each distinct combination becomes a separate group.
Detailed Explanation
Use a composite key, commonly an anonymous type, as the GroupBy key. Each distinct combination becomes a separate group.
The resulting group's Key exposes each component of the composite key.
Code Example
var result = sales
.GroupBy(s => new
{
s.Year,
s.Month
})
.Select(g => new
{
g.Key.Year,
g.Key.Month,
Total = g.Sum(x => x.Amount)
});