Exploring the Linq GroupBy Method in C# with Examples | 2023

LINQ GroupBy method is a powerful tool for grouping elements in a collection or sequence based on a common key value. It allows you to perform grouping operations similar to those in SQL and is commonly used in LINQ queries to perform grouping and aggregation operations on data.

The GroupBy the method takes one or more parameters:

  1. A key selector function extracts the key value from each element in the collection, which is used to group the elements together.
  2. An optional element selector function that transforms the elements in each group.
  3. An optional comparer that determines how the key values are compared.

Example of Linq Groupby Method

Assume we have an employee object stored in a database with the following properties in it. It also has some relational data like department.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public double Salary { get; set; }
}

In this scenario if we want to group the employees by department. We can utilize the group by the method in Linq.

List<Employee> employees = new List<Employee>
{
    new Employee { Id = 1, Name = "John", Department = "Sales", Salary = 50000 },
    new Employee { Id = 2, Name = "Jane", Department = "Marketing", Salary = 60000 },
    new Employee { Id = 3, Name = "Bob", Department = "Sales", Salary = 45000 },
    new Employee { Id = 4, Name = "Alice", Department = "Marketing", Salary = 55000 }
};

var groups = employees.GroupBy(e => e.Department);

foreach (var group in groups)
{
    Console.WriteLine($"Employees in {group.Key} department:");
    foreach (var employee in group)
    {
        Console.WriteLine($"- {employee.Name} ({employee.Salary:C})");
    }
}

Either we use the linq query to group by the collection or we use the extension method to achieve the same goal. Here we have utilized the extension method to do that.

In this example, we define a list of Employee objects with different Id, Name, Department, and Salary values. We then use the GroupBy method to group the employees by their Department property. We iterate over the groups using a foreach loop and print out the names and salaries of the employees in each group.

Employees in Sales department:
- John ($50,000.00)
- Bob ($45,000.00)
Employees in Marketing department:
- Jane ($60,000.00)
- Alice ($55,000.00)

Group by Collection Using Linq Query

Here’s an example of how to use LINQ queries to group a list of Employee objects by their Department property. Let’s utilize the same collection of employee objects which we initialized earlier.

var groups = from employee in employees
             group employee by employee.Department;

foreach (var group in groups)
{
    Console.WriteLine($"Employees in {group.Key} department:");
    foreach (var employee in group)
    {
        Console.WriteLine($"- {employee.Name} ({employee.Salary:C})");
    }
}

In this example, we define a list of Employee objects with different Id, Name, Department, and Salary values. We then use a LINQ query with the group by clause to group the employees by their Department property.

Multiple ways of iterating the group by elements

There are multiple ways to iterate over the groups and their elements after using the GroupBy method or a group by a clause in a LINQ query.

Using ForEach

Using a foreach loop on the IGrouping<TKey, TElement> the object returned by the GroupBy method.

var groups = employees.GroupBy(e => e.Department);

foreach (var group in groups)
{
    Console.WriteLine($"Employees in {group.Key} department:");
    foreach (var employee in group)
    {
        Console.WriteLine($"- {employee.Name} ({employee.Salary:C})");
    }
}

Using Linq Select

Using LINQ’s Select method to project each group into a new sequence of values.

var groups = employees.GroupBy(e => e.Department);

var groupData = groups.Select(g => new
{
    Department = g.Key,
    TotalSalary = g.Sum(e => e.Salary),
    AverageSalary = g.Average(e => e.Salary)
});

foreach (var data in groupData)
{
    Console.WriteLine($"Department: {data.Department}");
    Console.WriteLine($"Total salary: {data.TotalSalary:C}");
    Console.WriteLine($"Average salary: {data.AverageSalary:C}");
}

Nested ForEach

Using a nested foreach loop with LINQ’s Where method to filter the elements in each group.

var groups = employees.GroupBy(e => e.Department);

foreach (var group in groups)
{
    Console.WriteLine($"Employees in {group.Key} department with salary over $50,000:");
    foreach (var employee in group.Where(e => e.Salary > 50000))
    {
        Console.WriteLine($"- {employee.Name} ({employee.Salary:C})");
    }
}

Using Aggregate Function

var groups = employees.GroupBy(e => e.Department);

foreach (var group in groups)
{
    var totalSalary = group.Aggregate(0, (sum, e) => sum + e.Salary);
    Console.WriteLine($"Total salary for {group.Key} department: {totalSalary:C}");
}

As you can see, there are many ways to iterate over the groups and elements in a grouped collection or sequence using C# and LINQ. Each approach has its own advantages and disadvantages depending on the specific requirements of your application.

Linq Group By to Dictionary

After applying the GroupBy() method to a collection, you can easily convert the grouped elements into a dictionary by calling the ToDictionary() method. This conversion allows you to use the grouping key as the dictionary key and the grouped elements as the corresponding dictionary values.

var groupedEmployees = employees.GroupBy(e => e.Department)
                               .ToDictionary(g => g.Key, g => g.ToList());

In this code, GroupBy(e => e.Department) groups the employees list based on the Department property. It returns an IEnumerable<IGrouping<string, Employee>> where each grouping has a key (department) and a list of employees in that department.

Then, ToDictionary(g => g.Key, g => g.ToList()) converts the grouped results into a dictionary. The key of the dictionary is the department, and the value is the list of employees in that department. The resulting dictionary is of type Dictionary<string, List<Employee>>.

Now you can access the grouped data using the department as the key. For example, to retrieve all employees in the Sales department from the dictionary, you can do:

List<Employee> salesEmployees = groupedEmployees["Sales"];

Conclusion

In conclusion, the GroupBy method in LINQ is a powerful tool for grouping elements in a collection or sequence by a specified key. It allows for easy aggregation and manipulation of the groups and their elements using a variety of C# and LINQ features, such as foreach loops, LINQ queries, filtering, and aggregation.

By leveraging the flexibility and expressiveness of LINQ, developers can write concise, readable, and efficient code for complex data processing tasks.

Scroll to Top