The GroupBy
operator is a LINQ query operator that groups the elements of a sequence according to a specified key. The key is specified by a function that takes an element of the sequence as input and returns a value that is used to determine the group to which the element belongs.
Here are some examples of how you might use the GroupBy
operator in C#:
Example 1: Grouping a list of integers by their remainder when divided by a specific number:
1 2 3 4 | List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var groupedNumbers = numbers.GroupBy(n => n % 3); |
Example 2: Grouping a list of strings by their first letter:
1 2 3 4 | List<string> words = new List<string> { "apple", "banana", "cherry", "date", "elderberry" }; var groupedWords = words.GroupBy(w => w[0]); |
Example 3: Grouping a list of objects by a specific property:
1 2 3 4 | List<Product> products = GetProducts(); var groupedProducts = products.GroupBy(p => p.Category); |
Example 4: Grouping a list of objects by multiple properties:
1 2 3 4 | List<Order> orders = GetOrders(); var groupedOrders = orders.GroupBy(o => new { o.Customer.Country, o.Customer.City }); |
Example 5: Grouping a list of objects by a specific property and then sorting the groups by another property:
1 2 3 4 5 6 | List<Employee> employees = GetEmployees(); var groupedEmployees = employees.GroupBy(e => e.Department) .OrderBy(g => g.Key) .Select(g => new { Department = g.Key, Employees = g }); |
In these examples, the GroupBy
operator is used to group the elements of a sequence according to a specified key. The key is specified by a function that takes an element of the sequence as input and returns a value that is used to determine the group to which the element belongs.
In the first example, the GroupBy
operator is used to group a list of integers by their remainder when divided by a specific number. In the second example, the GroupBy
operator is used to group a list of strings by their first letter. In the third example, the GroupBy
operator is used to group a list of Product
objects by the Category
property. In the fourth example, the GroupBy
operator is used to group a list of Order
objects by multiple properties Country
and City
. In the fifth example, the GroupBy
operator is used to group a list of Employee
objects by the Department
property, OrderBy
operator is used to sort the groups by the Department
property and the Select
operator is used to create a new sequence of anonymous objects that contain the department and the group of employees.
It’s worth noting that GroupBy
operator returns an IEnumerable<IGrouping<TKey, TElement>>
, which is a sequence of IGrouping<TKey, TElement>
objects, where TKey is the type of the key and TElement is the type of the elements in the group.
[…] GroupBy: Groups the elements of a sequence according to a specified key […]