System.Linq.Enumerable.GroupBy Method

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

Overloads

public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey,TSource>> GroupBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource,TKey> keySelector)
public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey,TSource>> GroupBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource,TKey> keySelector, System.Collections.Generic.IEqualityComparer<TKey> comparer)
public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource,TKey> keySelector, System.Func<TKey,System.Collections.Generic.IEnumerable<TSource>,TResult> resultSelector)
public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource,TKey> keySelector, System.Func<TKey,System.Collections.Generic.IEnumerable<TSource>,TResult> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer)

Parameters

Return Value

Remarks

The GroupBy extension method groups the elements of the input sequence. The grouping is performed by applying the keySelector function to each element of the sequence.

If you do not specify a resultSelector function, the result is an enumeration of IGrouping<TKey,TSource> objects. Each IGrouping<TKey,TSource> object contains a key and an enumerable collection of elements that have that key.

If you specify a resultSelector function, that function is invoked for each group, and its return value forms the elements of the resulting sequence.

Examples

Example 1: Basic GroupBy

This example groups 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()
    {
        int[] numbers = { 5, 4, 1, 3, 2, 8, 6, 7, 9, 0 };

        // Group numbers by parity (even or odd)
        var groupedNumbers = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");

        foreach (var group in groupedNumbers)
        {
            Console.WriteLine($"Group: {group.Key}");
            foreach (var number in group)
            {
                Console.Write($"{number} ");
            }
            Console.WriteLine();
        }
    }
}
        

Example 2: GroupBy with Result Selector

This example groups a list of words by their starting letter and then counts the number of words in each group.


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

public class Example
{
    public static void Main()
    {
        string[] words = { "apple", "banana", "apricot", "blueberry", "cherry", "avocado" };

        // Group words by their first letter and count the number of words in each group
        var groupedCounts = words.GroupBy(
            w => w[0], // Key selector: first letter
            (letter, wordGroup) => new { Letter = letter, Count = wordGroup.Count() } // Result selector
        );

        foreach (var item in groupedCounts)
        {
            Console.WriteLine($"Starting with '{item.Letter}': {item.Count} words");
        }
    }
}
        

Example 3: GroupBy with Custom Equality Comparer

This example demonstrates grouping case-insensitively.


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

public class Example
{
    public static void Main()
    {
        string[] fruits = { "Apple", "banana", "Apricot", "Blueberry", "Cherry", "Avocado" };

        // Group fruits by their first letter, ignoring case
        var groupedFruits = fruits.GroupBy(
            f => f[0],
            (key, group) => new { Key = key, Values = group.ToList() },
            StringComparer.OrdinalIgnoreCase // Case-insensitive comparer
        );

        foreach (var group in groupedFruits)
        {
            Console.WriteLine($"Group: {group.Key}");
            foreach (var fruit in group.Values)
            {
                Console.Write($"{fruit} ");
            }
            Console.WriteLine();
        }
    }
}
        

See Also