Linq GroupBy in C#

LINQ (Language Integrated Query) is a powerful language feature in C# that allows you to query data from different sources such as arrays, lists, databases, and XML documents. One of the most commonly used LINQ operators is GroupBy, which allows you to group data based on a common key. In this lesson, we will learn how to use GroupBy in C#.

Let’s assume we have a collection of objects that contain information about different students in a class. Each student has a Name, Age, and Grade. We want to group this collection based on the Grade. To achieve this, we can use the GroupBy operator.

Here’s the code to achieve this:
var students = new List<Student>
{
    new Student { Name = "John", Age = 25, Grade = "A" },
    new Student { Name = "Jane", Age = 28, Grade = "B" },
    new Student { Name = "Bob", Age = 30, Grade = "A" },
    new Student { Name = "Sue", Age = 25, Grade = "B" },
    new Student { Name = "Bill", Age = 25, Grade = "C" },
};

var groupedStudents = students.GroupBy(student => student.Grade);

foreach (var gradeGroup in groupedStudents)
{
    Console.WriteLine($"Students in Grade {gradeGroup.Key}: {gradeGroup.Count()}");
    foreach (var student in gradeGroup)
    {
        Console.WriteLine($"\t{student.Name} - {student.Age} years old");
    }
}

In the above code, we first create a list of Student objects. We then use the GroupBy operator to group the students by Grade. This returns a collection of groups where each group represents students in a particular grade.

We then iterate through the groupedStudents collection and print the information about the students in each group.

The output of the above code would be:
Students in Grade A: 2
    John - 25 years old
    Bob - 30 years old
Students in Grade B: 2
    Jane - 28 years old
    Sue - 25 years old
Students in Grade C: 1
    Bill - 25 years old

As we can see, the students are grouped by Grade, and we get a separate group for each grade. Each group contains a list of students in that grade.

In conclusion, LINQ GroupBy in C# is a powerful feature that allows you to efficiently group data from different sources. By using this feature, you can easily query complex data sets and extract meaningful insights from them.