top of page

How to Achieve Group By in C# LINQ

Updated: May 3, 2023

Group by in C# LINQ is a query that groups the elements of a sequence according to a specified key selector function. The key can be a property of the element, a value derived from the element, or an expression involving the element. The grouping operation returns an IEnumerable<IGrouping<TKey, TElement>> object that contains a key and a sequence of elements that match that key. In this article, we will learn How to Achieve Group By in C# LINQ.


Group by in C# LINQ can be used to:

  • Organize the data into categories based on a common attribute or value.

  • Perform aggregate functions or other methods on each group to perform calculations or transformations.

  • Project the results into a new form that contains the key and the group data.

For example, you can use group by in C# LINQ to:

  • Find the number of employees in each department based on the department ID.

  • Find the average score of students in each grade based on the grade level.

  • Find the products and their total sales in each category based on the category ID.

Before going further you may be interested in the following articles.


How to Achieve Group By in C# LINQ

Follow the below steps to achieve group by in C# LINQ:


STEP 1: Define the data source that you want to group. For example, you can use a collection of objects, such as employees or students.


STEP 2: Use the group keyword to group the elements of the data source by a common key. The key can be a property of the element, a value derived from the element, or a compound key composed of multiple properties or values. For example, you can group employees by their department ID or by the first letter of their last name.


STEP 3: Use the into keyword to create a new identifier for each group. The identifier represents an IGrouping<TKey, TElement> object that contains the key and all the matching elements for that key. For example, you can create an identifier for each department ID that contains all the employees in that department.


STEP 4: Use the select keyword to project the results into a new form. You can use anonymous types or named types to create the output. For example, you can select the department ID and the number of employees for each group.


Here is an example to achieve group by in C# LINQ:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Define the data sourcevar employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Alice", DepartmentId = 1 },
            new Employee { Id = 2, Name = "Bob", DepartmentId = 2 },
            new Employee { Id = 3, Name = "Charlie", DepartmentId = 1 },
            new Employee { Id = 4, Name = "David", DepartmentId = 3 },
            new Employee { Id = 5, Name = "Eve", DepartmentId = 2 }
        };

        // Perform group by using LINQvar query = from e in employees
                    group e by e.DepartmentId into g
                    select new
                    {
                        DepartmentId = g.Key,
                        EmployeeCount = g.Count()
                    };

        // Display the resultsforeach (var result in query)
        {
            Console.WriteLine($"Department {result.DepartmentId} has {result.EmployeeCount} employees");
        }

        Console.ReadLine();
    }
}

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int DepartmentId { get; set; }
}

Output:

Group By in C# LINQ- output

The above code defines a class Employee, which represents an employee object with an Id, Name, and DepartmentId property. It then creates a list of employees, employees, with several instances of this class.


The code then performs a group by query on this list using LINQ, grouping the employees by their DepartmentId property. The results of this query are stored in an anonymous type, which contains the DepartmentId and the number of employees in that department.


Finally, the code loops through the results of the query and displays them to the console.


0 comments

Comments


bottom of page