C# Linq

LINQ GroupBy Operator in C# with Examples

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:

Example 2: Grouping a list of strings by their first letter:

Example 3: Grouping a list of objects by a specific property:

Example 4: Grouping a list of objects by multiple properties:

Example 5: Grouping a list of objects by a specific property and then sorting the groups by another property:

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.

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.