C# – LINQ GroupBy Examples

GroupBy is a LINQ functionality which allows to group items from a collection based on a given key. It’s an equivalent to SQL’s GROUP BY clause. In this article we’ll show various examples of usage, starting from the simplest grouping by one key, through grouping by multiple keys, custom result selector and all of that in two variants: Lambda and Query expression.

Let’s prepare sample data which we could operate on to present various examples of group by. For this purpose we define Person class and create 10 objects collected within a list.

Single key selector

First scenario is to group people collection by forename.

Lambda expression
Query expression

Both Lambda and Query expression generates the same results which can be displayed with foreach loops. We need to use two of them as first level is collection of groups and each group contains collection of people within particular group.

In the results we can see four groups, where people within each group share the same forename.

Multiple key selector

Above example was the simplest but it is also possible to group by multiple keys. To present it let’s group our people collection by both forename and age.

Lamda expression
Query expression

Results can be printed using the code from previous example. This time we’ve got seven groups of people, where each group contains only people with the same forename and age.

Custom result selector

Last example I’d like to present here is combining group by with custom result selector. In this scenario each group in the returned collection has GroupName property containing a key name, GroupSize property containing number of items in a group, and GroupItems containing list of people in a group.

Lambda expression
Query expression

Code to display results needs to be slightly modified to reflect above selector changes.