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.

What are lambda expressions

In this post i want to talk about lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". In other words, lambda expression can be broken down into parameters followed by execution code:

Parameter => executioncode.

The  left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. The lambda expression x=> x * x  is read " x goes to x times x". In other words we want to square any given number and to do this we are going to assign to a delegate type as follows:



 







Result: The square of 5 is 25.

The => operator has the same precedence as assignment (=) and is right-associative.

Lambdas can be used in method-based LINQ queries as arguments to standard query operator methods such as Where. Let us look at the following pratical example:




























I have my object Person that i can model into a list of anything that represents a person, for instance, in this case i have modeled it to give me a list of Students. Now that we have our Students, we can go ahead and filter the Students by their Age, in this example i want to return teenagers or independents.

Both "getTeenagers()" and "getIndependents()" uses a lambda expression as a predicate to compare each Student's Age and return a  new collection of Students in their respective Age group.

For more on Lambda expressions you can read this article.