Thursday 15 September 2011

Linq equivalent to SQL Select Count and Group by

In this post i want to show you how you can do a select count and group by using LINQ that is equivalent to SQL's.
















We have our object Student and we are going to create a list of Students. Now we want to return a list of Students who are in a certain Class and the number of Students in that Class. To do that we are going to use the GroupBy method and use a lambda expression to return the group of Students in a Class as a list. From the list we can then select the Class name and the Count. Take note that I used an anonymous type in the Select method.




Now if we want to group by more than one field, for instance, Subject in this case here is how we can do it:


Results:



Hope you found this post useful. Like to hear from you for suggestions or questions.

No comments:

Post a Comment