Enumerable.GroupBy Method

Groups the elements of a sequence according to a specified key selector function.

public static IEnumerable<TSource> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector )

Description

The GroupBy method projects each element of a sequence into an element of type TResult. This overloaded version of GroupBy groups the elements of an IEnumerable<TSource> based on a key derived from each element. The grouping is performed by a specified key selector function.

This method performs deferred execution.

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<TSource> whose elements to group.
keySelector Func<TSource, TKey> A function to extract the key from each element.

Returns

Type Description
IEnumerable<IGrouping<TKey, TSource>> An IEnumerable<IGrouping<TKey, TSource>> where each grouping contains elements that share the same key.

Example

The following code example demonstrates how to use the GroupBy method to group a list of numbers by whether they are even or odd.

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> numbers = new List<int> { 5, 4, 2, 3, 1, 1, 6, 8, 7, 9, 10 }; // Group numbers by whether they are even or odd var groupedNumbers = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd"); // Print the groups foreach (var group in groupedNumbers) { Console.WriteLine($"Group: {group.Key}"); foreach (var number in group) { Console.Write($"{number} "); } Console.WriteLine(); } } }

Output:

Group: Odd 5 3 1 1 7 9 Group: Even 4 2 6 8 10