Group by using C# LINQ

By | March 24, 2017

Hello, In this article I will discuss how to achieve the group 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 in C#.

Become an Expert in Programming and Web Development.View all courses!

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<TKey, T> 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 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).

 

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.

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.

Lets see the result in below figure.

 

Conclusion:

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

Category: C#