Site Loader
Auckland, New Zealand
In last post we saw what grouping is and how we can perform grouping of collection with single property and with a predicate. In this post we are going to write some more complex query and method syntax in LINQ for grouping. We are going to take our custom class (Student)

And here are the list of students

Let’s jump start with our examples

Example 1 – Grouping and Ordering with Single Property

In this example we are once again work with single property of collection, but this time as opposed to last post, we are going to not just group the data, but also order the data in ascending.   Here is the output

You can not the following from the output shown above

The Group names and Student names are ordered by Ascending.

Example 2 – Working with Compound Keys

In this example we are going to go a little further and see how we can still customize the above example. Here we are going to use two keys (Compound keys) for grouping and order them based on the key. In this example, we are going to group students based on Department and by classes and also we are going to order the department and class by Ascending. At last we are also going to order all the student names and Student ID.

We can write the same by Query syntax as shown below

The output will look like this

Let’s first understand the compound key (Department and Class) we have used in groupby extension method. As you can see in the groupby() extension method, we have created Anonymous method new {..} and selected Department and Class. Now Department and Class are the two compound keys available in all extension methods, so that we can use the Key property to consume and use them. Hence we have used them in both Orderby and Select extension methods and got the following result. I hope now you will have a clear understanding of how grouping is done in LINQ. 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 *