- In a single property
- By predicates
- In multiple properties (Compound keys)
- By some computed ranges
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 propertyIn 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|
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 PredicatesIn 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