C# GroupBy: How to Use

In C#, the GroupBy method is used to group elements in a collection based on a specific key. It returns an IEnumerable> object containing the grouped results, where TKey is the type of the key for the grouping and TElement is the type of the elements in the collection.

The GroupBy method has multiple overload forms, with the most common form taking a Func parameter that defines the selector function for grouping keys. For example, the following example groups a collection of strings by their length.

List<string> strings = new List<string> { "apple", "banana", "orange", "pear", "grape" };

var groups = strings.GroupBy(s => s.Length);

foreach (var group in groups)
{
    Console.WriteLine($"Group key: {group.Key}");
    foreach (var element in group)
    {
        Console.WriteLine($"Element: {element}");
    }
    Console.WriteLine();
}

Output:

Group key: 5
Element: apple
Element: grape

Group key: 6
Element: banana

Group key: 6
Element: orange

Group key: 4
Element: pear

In the above example, the strings.GroupBy(s => s.Length) method groups a collection of strings based on their length and returns an IEnumerable> object with 4 groups. Each group has a key (the length of the strings) that can be accessed using group.Key. Each group is an iterable collection that can be accessed using group.

bannerAds