Roadmap › LINQ — Language Integrated Query › Module: Grouping, Joins and Aggregation
Lessons in this course (12)

5. Grouping

Intermediate★ Must knowLesson 5 of 12
csharp
var byCategory = products
    .GroupBy(p => p.Category)
    .Select(g => new
    {
        Category = g.Key,
        Count = g.Count(),
        TotalValue = g.Sum(p => p.Price * p.Stock),
        MostExpensive = g.MaxBy(p => p.Price)!.Name
    });

// query syntax with 'into'
var q = from p in products
        group p by p.Category into g
        where g.Count() > 1
        select new { g.Key, Avg = g.Average(p => p.Price) };

// group by multiple keys (anonymous type)
var multi = orders.GroupBy(o => new { o.CustomerId, o.OrderDate.Year });

// ToLookup: immediate, re-usable grouping (key -> IEnumerable)
ILookup<string, Product> lookup = products.ToLookup(p => p.Category);
var furniture = lookup["Furniture"];               // empty sequence if key missing (no exception)

// .NET 9 shortcuts
var counts = products.CountBy(p => p.Category);                     // KeyValuePair<string,int>
var totals = products.AggregateBy(p => p.Category, 0m, (sum, p) => sum + p.Price);