(C# Language) LINQ - GroupBy

C# Linq provides a GroupBy extension method for grouping records on a common key. This tutorial starts with a brief introduction to the concept of grouping. Then we use the GroupBy extension to group various records on a property called last name so that customers of the same last name are grouped together. The result is then displayed on console.
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Create a Project

Create a C# console project for the latest version of .NET Core. Open the solution explorer and add a file called StudentData.cs.


// studentdata.cs file 
// a record to hold and provide seed data 

internal record class StudentData (
      String FirstName, String LastName, List<int> Marks)
{
  public static List<StudentData> Students = new() {
            new("Amelia", "Fletcher", new() {20, 30, 50 }),
            new("John", "Doe", new() {92, 13, 60 }),
            new("Sara", "Adams", new() {32, 33, 30 }),
            new("Lisa", "Bell", new() {72, 30, 60 }),
            new("James", "Bennett", new() {23, 33, 45 }),
            new("Teddy", "Fletcher", new() {45, 26, 51 }),
            new("Graham", "Bell", new() {25, 13, 53 }),
            new("Jose", "Fletcher", new() {25, 35, 65 }),
          };
}

Add a record class to hold StudentData consisting of FirstName, LastName and a list of marks in three subjects.

Since this is a tutorial, we can add a static member that provides us with some data. We have repeated a few last names for purposes of grouping.

Video Explanation (see it happen!)

Please watch the following youtube video:

What is Grouping

Grouping is a fairly complex topic that is taught in relational database courses.

Here I will try to get you started. I will explain it in the simplest possible language that might not be technically very accurate. But I think I will be able to explain the concept from a practical perspective.

Grouping is basically done on a common property of various records of a table. For example, we can do a grouping on last names because many customers can have the same last name. The last name is called a key. We could also have done grouping on the first character of a name because there are always people whose names start with "A", whose names start with "B" and so on. The first character is called a key.

The basic point here is that we would want to get a list of keys with each key containing a list of records grouped with that key. A grouping is, therefore, a list of lists.

"A group is, therefore, a list of lists."

So we would want to obtain a list of last names with each last name containing a list of customers who share that last name. This is analogous to creating the index of a book. An index is a list of lists.

Grouping with LINQ

Let's now run a grouping on the dataset we created.

Open the program.cs file so that we can write our program.

First write the GroupBy function on the list of StudentData records.

We have passed two arguments to this function. The first is a lambda that specifies the key for the groups. We have set the last name as the key key => key.LastName.


// GroupBy extension method 

var grouping = StudentData.Students.GroupBy(
        key => key.LastName,
        item => new { 
                      FName = item.FirstName, 
                      LName = item.LastName 
                    }
      );

foreach (var v in grouping)
{
  Console.WriteLine(v.Key);

  foreach (var stu in v)
  {
    Console.WriteLine($"\t{stu.FName} {stu.LName}");
  }
}

The second argument is an anonymous with properties FName and LName. Objects of this anonymous type will be grouped under the key.

This means that the key will contain a list of FName/LName items.

Now we can run a foreach loop on the grouping obtained above. First we print the key. After that a nested for-each loop prints the FName and LName properties.

Run the Project

Let's run the project. We can verify that the grouping occurs on the last names. Students with the same last names are listed under the key for the last name.


// output display 

Fletcher
        Amelia Fletcher
        Teddy Fletcher
        Jose Fletcher
Doe
        John Doe
Adams
        Sara Adams
Bell
        Lisa Bell
        Graham Bell
Bennett
        James Bennett


This Blog Post/Article "(C# Language) LINQ - GroupBy" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.