Skip Navigation Links
Electric Harbour
Danish Alt Codes
Finnish Alt Codes
French Alt Codes
Norwegian Alt Codes
Spanish Alt Codes
Scandanavian Alt Codes
Swedish Alt Codes
Bulk Identity Insert
SQL Server Constraints
Visual Studio Shortcuts
LINQ Cast Operator
LINQ Group By Example
LINQ Not In Example
LINQ Order By Example
CSV String Generator
Curriculum Vitæ

LINQ Group By Example - Group By Query Expression and Lambda Expression in C#

To me the LINQ group by syntax is a little counter intuitive. At least I never seem to be able to write a group by expression off the top of my head. Here is a very simple example of a group by statement using both query expressions and lambda expressions.

Query Expression:

var queryBreedsCount = (from x in dogs
                        group x by x.Breed into grp
                        select new {
                            Breed = grp.Key,
                            Count = grp.Count()

Lambda Expression:

var lambdaBreedsCount = dogs.GroupBy(x=>x.Breed).Select(grp => 
                        new {
                            Breed = grp.Key, 
                            Count = grp.Count() 

These statements do the exact same thing. In these queries I am using the Count operator but you can use the Sum operator instead or another aggregate operator of your choosing.