C# GroupBy: Explained Simply
In C#, the GroupBy function is used to group elements in a collection based on a specified key. It returns a sequence of groups grouped by the key, with each group containing elements with the same key.
The GroupBy method can be applied to any collection that implements the IEnumerable interface, including arrays, lists, and query results. You can use lambda expressions or delegates to specify the grouping key.
Each element in the returned sequence of groups is an IGrouping
By using the GroupBy method, it is easy to group elements in a collection for further processing, analysis, or aggregation. For example, you can use the GroupBy method to group students by class, orders by customer, products by category, etc.
Here is an example demonstrating how to use the GroupBy method to group an integer list by even and odd numbers.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var groups = numbers.GroupBy(x => x % 2 == 0 ? "偶数" : "奇数");
foreach (var group in groups)
{
Console.WriteLine($"Key: {group.Key}");
foreach (var number in group)
{
Console.WriteLine(number);
}
}
The output will be:
Key: 奇数
1
3
5
7
9
Key: 偶数
2
4
6
8
10
It can be seen that the elements have been successfully grouped by their odd and even keys. Each group contains a key and its corresponding element.