Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.GroupBy — grouping by a key

Enumerable.GroupBy divides a sequence into groups using a selected key. Each group exposes its key through Key, and its elements can be enumerated directly as a sequence.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

IEnumerable<IGrouping<TKey, TSource>> groups = source.GroupBy(keySelector);
IEnumerable<IGrouping<TKey, TElement>> groups = source.GroupBy(keySelector, elementSelector);

Enumerable.GroupBy in System.Linq groups by keySelector. Without elementSelector, it retains source elements; with it, it stores their projected values.

These overloads return IEnumerable<IGrouping<TKey,TElement>>. IGrouping<TKey,TElement> implements IEnumerable<TElement>: the group itself is the sequence of elements, not an object with a separate Values collection. The IGrouping<TKey,TElement>.Key property returns the shared key. Without projection, TElement is the source element type.

Execution is deferred until enumeration. Groups follow first-key occurrence order, and elements retain source order; keys are not sorted. Equality defaults to EqualityComparer<TKey>.Default; supply IEqualityComparer<TKey> for another comparison.

The .NET 10 example groups words by length. group.Key is the length, and elements refers to the group itself.

Examples

using System;
using System.Collections.Generic;
using System.Linq;

string[] words = { "pear", "fig", "plum", "kiwi", "tea" };
IEnumerable<IGrouping<int, string>> groups = words.GroupBy(word => word.Length);

foreach (IGrouping<int, string> group in groups)
{
    IEnumerable<string> elements = group;
    Console.WriteLine($"{group.Key}: {string.Join(", ", elements)}");
}

Result

4: pear, plum, kiwi
3: fig, tea

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources