Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

LINQ CountBy() and AggregateBy() methods

Reference for LINQ CountBy() and AggregateBy() in C#: count and fold elements per key in one pass, without the groups that GroupBy() allocates.

CountBy() and AggregateBy() arrived in .NET 9. Both group elements by a key and compute one value per key, but unlike GroupBy() they never build the groups themselves. Each element is folded into a running value for its key, so they use less memory and one pass over the data.

CountBy() returns KeyValuePair<TKey, int> entries with the number of elements per key. AggregateBy() is the general form: you provide a seed and a function that merges each element into the per-key accumulator.

C#
foreach (var (letter, n) in text.CountBy(c => c)) { }
var totals = orders.AggregateBy(o => o.Customer, 0m, (sum, o) => sum + o.Total);

Try it

C# Counting per key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Folding per key with AggregateBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static IEnumerable<KeyValuePair<TKey, int>> CountBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IEqualityComparer<TKey>? keyComparer = null) where TKey : notnull;

public static IEnumerable<KeyValuePair<TKey, TAccumulate>> AggregateBy<TSource, TKey, TAccumulate>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    TAccumulate seed,
    Func<TAccumulate, TSource, TAccumulate> func,
    IEqualityComparer<TKey>? keyComparer = null) where TKey : notnull;

public static IEnumerable<KeyValuePair<TKey, TAccumulate>> AggregateBy<TSource, TKey, TAccumulate>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TKey, TAccumulate> seedSelector,
    Func<TAccumulate, TSource, TAccumulate> func,
    IEqualityComparer<TKey>? keyComparer = null) where TKey : notnull;
Name Description
keySelector Computes the grouping key of an element. Keys must not be null.
seed Starting accumulator for each new key (the same value is used for every key).
seedSelector Creates the starting accumulator for a key; use it for mutable accumulators.
func Combines the current accumulator with an element and returns the new accumulator.
keyComparer Optional equality comparer for keys.

Returns: a sequence of key/value pairs, one per distinct key, in order of first appearance of each key in practice (not documented as a guarantee).

Errors: ArgumentNullException for null arguments. A null key raises ArgumentNullException during enumeration.

Usage notes

  • Requires .NET 9 or later. Older targets must use GroupBy() followed by Count() or Aggregate().
  • Deferred, but a full pass. Enumeration reads the whole source before the first pair is returned.
  • Do not rely on result order. Sort the pairs with OrderBy() before printing, as the examples do.
  • Mutable seeds. AggregateBy(key, new List<int>(), ...) shares one list among all keys. Use the seedSelector overload to create a fresh accumulator per key.
  • Why not GroupBy()? GroupBy() keeps every element of every group. When you only need a count, a sum or a min, CountBy() and AggregateBy() keep one value per key.
  • Deconstruction. KeyValuePair<TKey, TValue> deconstructs, so foreach (var (key, value) in ...) works.
  • Not an IQueryable operator. Database providers translate GroupBy() queries; these two operate in memory.
  • Dictionary alternative. Before .NET 9 the idiom was ToDictionary() after GroupBy(), or a manual loop with CollectionsMarshal.GetValueRefOrAddDefault().