C# Interview Question #48
What is GroupBy() in LINQ?
LINQ & Querying Mid-Level Intermediate
Quick Interview Answer
GroupBy organizes elements into groups based on a key. Each group has a Key and a sequence of matching elements.
Detailed Explanation
GroupBy organizes elements into groups based on a key. Each group has a Key and a sequence of matching elements.
It is useful for summaries, reports, analytics, and aggregation. Common aggregate operations used with grouping include Count, Sum, Average, Min, and Max.
When using EF Core, whether a GroupBy expression is translated to SQL depends on the query shape and provider capabilities, so generated SQL should be reviewed for performance-sensitive queries.
Code Example
var result = products
.GroupBy(p => p.CategoryId)
.Select(g => new
{
CategoryId = g.Key,
ProductCount = g.Count(),
TotalValue = g.Sum(p => p.Price)
});