Using LINQ to Group By Multiple Values

I recently wrote some code using LINQ in which I had to perform a grouping by multiple values. It had been a little while since I'd made use of LINQ's GroupBy method and couldn't remember how to group by multiple values.

The answer is to use anonymous types. Here's an example of how to group a list of Car objects by their Make and Model properties:

var carGroups = cars.GroupBy(x => new { Make = x.Make, Model = x.Model }); 

And here's an example of how to group the same list by the same properties, but only when the group contains 5 or more objects:

var carGroups = cars.GroupBy(x => new { Make = x.Make, Model = x.Model })
                .Where(grp => grp.Count() >= 5);

The properties of your anonymous object can be accessed via the group's Key property. Here's an example, using the groups we created in the previous example:

foreach (var group in carGroups)
        String.Format("Make {0}, Model {1}", group.Key.Make, group.Key.Model));

It's the simplicity of things like this that makes me love LINQ. :)


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

A Red Herring When Using Moq to Mock Methods With Optional Parameters