GroupBy: The SQL counterpart in LINQ
On this page
Categorizing Data
GroupBy is arguably the most powerful tool in the LINQ toolkit. It allows you to organize your data into buckets based on a key.
1. The IGrouping Structure
Unlike other LINQ methods, GroupBy returns an IEnumerable<IGrouping<K, T>>. An IGrouping is a special type that has a Key property and also acts as a collection of the items that match that key.
2. Server-side Grouping
In EF Core, GroupBy is translated into a SQL GROUP BY. This allows you to perform massive aggregations (like 'Total sales per region') on the server and only return the results.
var salesPerRegion = orders
.GroupBy(o => o.Region)
.Select(g => new {
Region = g.Key,
Total = g.Sum(o => o.Amount)
});
3. Architect Insight
Q: "What is 'GroupBy with Multiple Keys'?"
Architect Answer: "You can group by an anonymous type: .GroupBy(x => new { x.Year, x.Month }). This is incredibly useful for temporal data analysis. Just remember that if you are using in-memory collections, anonymous types handle equality by value, so this works perfectly; but for custom classes, you must ensure equality logic is correct."