GroupBy is arguably the most powerful tool in the LINQ toolkit. It allows you to organize your data into buckets based on a key.
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.
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)
});
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."