← Back

New AggregateBy LINQ Method

2026-01-02 19:04 · 👁 2

🚀 What’s New in C#: The New AggregateBy LINQ Method

If you’ve ever written GroupBy(...).Select(g => ...) just to sum, count, or accumulate values by a key, the new AggregateBy LINQ method is for you.

Introduced in .NET 9 / C# 13, AggregateBy allows you to aggregate directly by key without creating intermediate groupings.

🧠 What is AggregateBy?

Think of it as Aggregate, but grouped by a key.

Instead of producing IGrouping<TKey, TElement> like GroupBy, it:

Uses a key selector

Maintains an accumulator per key

Returns (Key, Accumulator) pairs

This makes it ideal for simple and efficient “group + aggregate” scenarios.

✍️ Before vs After ❌ Traditional approach with GroupBy

var totals = sales
    .GroupBy(s => s.Product)
    .Select(g => new 
    { 
        Product = g.Key, 
        Total = g.Sum(x => x.Quantity) 
    })
    .ToDictionary(x => x.Product, x => x.Total);

✅ Using AggregateBy

var totals = sales
    .AggregateBy(
        keySelector: s => s.Product,
        seed: 0,
        func: (acc, s) => acc + s.Quantity)
    .ToDictionary(x => x.Key, x => x.Value);

👉 Key difference: No IGrouping, no projection step — just direct aggregation per key.

🎯 When AggregateBy Really Shines

Totals or counts per key (sales per product, requests per endpoint, errors per type)

Custom accumulators (build DTOs, track min/max, keep last value, etc.)

Large collections where avoiding extra allocations matters

It’s especially useful when you don’t actually need a group — just the result.


#csharp #dotnet #developerexperience #cleanCode

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please reload the page.