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
The GroupBy method has multiple overload forms, with the most common form taking a Func
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