top of page

Linq Group By in C# with easy code example

Updated: Mar 14, 2023

Hello, In this article I will discuss how to achieve the grouping by of data in C# LINQ. The grouping of data in C# linq is different from the SQL grouping. Lets see the examples and explanations LINQ Group by in C# with code.


Also read :


How Group by works with C# Linq

If we group by using the SQL clause we get the flat record set. If I have a set of the data of employee which has employee ID and if a group by the sql group by departmentid, anything else that is specific to the employee has to be aggregated somehow by using Sum, Min or Max , or may be aggregate.


I can get the count of the employees by department id or I can get the min and max. And once I use the group by it is difficult to get into the individual values associated with each group in SQL group by.


In Linq group by clause we can still get the individual elements. As it creates a sequence of Groups. The groups implements the IGrouping where TKey is the attribute on which you grouped on and T represents the original entity .


I have some collection of groups and inside those groups I have individual elements. It is generally a hierarchical data structure.


Lets see an example of LINQ group by using comprehension query syntax. Here generally the query ends with group by or select. I am grouping the below data by department id.


But my query does not end there. I am using a into keyword which is basically a range variable. It is like a second query after the into keyword. Once we start the other query with into keyword its like the second query. And I am ordering my data from the first part by inserting into depGroup by Key(DepartmentID).


class Program
    {
        private static IList employeeList = GetEmployees();

        return new List() {
 new Employee() { ID = 1, DepartmentID = 1, Name = "Vikram" },
 new Employee() { ID = 2, DepartmentID = 2, Name = "George" },
 new Employee() { ID = 3, DepartmentID = 1, Name = "Bush" },
 new Employee() { ID = 4, DepartmentID = 3, Name = "Donald" },
 new Employee() { ID = 5, DepartmentID = 1, Name = "Vishnu" },
 new Employee() { ID = 6, DepartmentID = 3, Name = "Visihi" },
 };

        static void Main(string[] args)
        {
            var groupedList = from employee in employeeList
                              group employee by employee.DepartmentID into depGroup
                              orderby depGroup.Key ascending
                              select depGroup;

            foreach (var group in groupedList)
            {
                Console.WriteLine(string.Format("Dep ID: {0}", group.Key));
                foreach (var employee in group)
                {
                    Console.WriteLine(string.Format("\t Employee: {0}", employee.Name));
                }
            }

            Console.Read();
        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int DepartmentID { get; set; }
    }

Lets see the result in the below figure.



Group by Composite Key

Now suppose if we want to group by the same LINQ by two properties basically a composite key. We can create an anonymous type and use it for grouping.

 static void Main(string[] args)
        {
            var groupedList = from employee in employeeList
                              group employee by new { employee.DepartmentID, FirstLetter = employee.Name[0] };
                           

            foreach (var group in groupedList)
            {
                Console.WriteLine(string.Format("Dep ID: {0}", group.Key.DepartmentID, group.Key.FirstLetter));
                foreach (var employee in group)
                {
                    Console.WriteLine(string.Format("\t Employee: {0}", employee.Name
                        ));
                }
            }

            Console.Read();
        }

In the above code I am grouping by DepartmentID and FirstLetter of Name. Any guess what the output will be. Run the code and see the result.


Projections Using Group by

Now there can be a case where we want to project the grouped by result into some other result type.

In that case we can use projection by creating an a anonymous type in the final select statement.


Suppose using the above data if I want to calculate the total number of employees for each department which have same initial letter I can use the below query.

  static void Main(string[] args)
        {
            var groupedList = from employee in employeeList
                              group employee by new { employee.DepartmentID, FirstLetter = employee.Name[0] } 
                              into newGroup
                              select new {
                                  DepartmentID = newGroup.Key.DepartmentID,
                                  Count = newGroup.Count(),
                                  Employees = newGroup
                              };

                           

            foreach (var group in groupedList)
            {
                Console.WriteLine("DID : {0}, Count: {1} ", group.DepartmentID, group.Count);
                foreach (var employee in group.Employees)
                {
                    Console.WriteLine("\t {0} : {1}", employee.DepartmentID, employee.Name);
                }
            }

            Console.Read();
        }

Lets see the result in below figure.



Conclusion:

In this article I have showed how we can work with LINQ group by clause with C#. I have also shown the projections with we can create by using LINQ group by.


Source: Paper.li

0 comments

Comments


bottom of page