Site Loader
Auckland, New Zealand
Grouping is one of the important and most powerful extension method available in LINQ. Grouping transforms a collection into a group specified in the key. In this post we are going to deep dive into what grouping is and how to work with GroupBy() extension method available in LINQ. Grouping can be done either
  • In a single property
  • By predicates
  • In multiple properties (Compound keys)
  • By some computed ranges
We will discuss most of them in very detail in this blog post. In this example we are going to take our same custom class (Student), but I have added one more property called Department to better illustrate the scenarios of Grouping.

Here is the data which I have populated to create some students

As you can see above, I have created some students and they belong to some departments like CSC, Math and BIO. Now we are going to deal with these data and understand how grouping will really work.

Example 1 – Grouping collection by single property

In this example we are going to group students by Department

As you can see from the above code, we have used GroupBy() extension method and we have used lambda expression to group based on Department. In the iteration of foreach loop, we have listed the students department by student.key
Note: Remember as mentioned first, in GroupBy() extension method, collections are grouped based on Key, in the above example the key is Department and hence during iteration, we are getting the department name from key and here the value is the student class itself
Here is how it looks like in Visual studio intellisense

And there is one more foreach loop where we have got all the students details selected (Name and StudID)


As you can see from the above output, we have grouped all the students based on their departments. We can write the same method syntax into Query syntax as

Example 2 – Grouping by Predicates

In this example we are group students by certain conditions, let’s say by StudID greater than 103.

As you can see we have given a predicate condition (which returns bool) and grouping students based on the condition. Now the output looks like this


As you can see the output, we have two groups, one is False, which include the students name and ID which has not satisfied our condition, whereas the opposite is for our true group. I hope this initial start of grouping might have given you all a good idea of what grouping is in LINQ, we will discuss more on grouping in our next post. Please leave your comments and thanks for reading !!! Thanks, Karthik KK

Post Author: Karthik kk

Leave a Reply

Your email address will not be published. Required fields are marked *