Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

LINQ GroupBy() method

Reference for LINQ GroupBy() in C#: group by one or several keys, project group results, count and sum per group, ordering and deferred execution.

GroupBy() splits a sequence into groups of elements that share the same key. Each group is an IGrouping<TKey, TElement>: a sequence of the group's elements that also has a Key property. The result is a sequence of those groups.

It is the LINQ counterpart of SQL GROUP BY. Combine it with Select() to compute counts, sums or averages per group. Groups appear in the order in which their keys are first seen in the source, and elements inside a group keep their source order.

C#
var byLength = words.GroupBy(w => w.Length);
var totals = sales.GroupBy(s => s.Region, s => s.Amount, (region, amounts) => (region, amounts.Sum()));

Try it

C# Grouping and aggregating

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# Composite keys and result selectors

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<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector);
public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
    Func<TKey, IEnumerable<TSource>, TResult> resultSelector);
// more overloads add an IEqualityComparer<TKey>? and both selectors together
Name Description
keySelector Computes the grouping key for each element.
elementSelector Optional. Chooses what goes into the group (default: the element itself).
resultSelector Optional. Turns a key and its elements into one result instead of an IGrouping.
comparer Optional IEqualityComparer<TKey>, for example StringComparer.OrdinalIgnoreCase.

Returns: a lazy sequence of groups, or of your results when a result selector is used.

Errors: ArgumentNullException for a null source or selector. A null key is allowed and forms its own group.

Usage notes

  • Execution: enumerating the result reads the whole source once and builds an internal lookup, so memory use is O(n). Group order follows first appearance of each key.
  • Keys use equality, not reference identity of anonymous objects. Tuples, records and anonymous types compare by value, so they are good composite keys. A plain class without Equals() and GetHashCode() makes every element its own group.
  • Case-insensitive grouping: pass StringComparer.OrdinalIgnoreCase; the group key is the first spelling encountered.
  • Different from ToLookup(): GroupBy() is deferred and re-evaluates on each enumeration; ToLookup() runs immediately and gives indexed access by key.
  • Groups are not sorted. Add OrderBy(g => g.Key) if you need ordered output.
  • Entity Framework can translate GroupBy().Select() with aggregates into SQL; avoid touching the group elements in ways that force client evaluation.
  • Counting per key is what CountBy() (.NET 9+) does without creating groups.
  • Query syntax: from s in sales group s by s.Region into g select ....