Showing posts from June, 2013

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) {     Console.WriteLine(         String.Format("Make {0}, Model {1}", group.Key.Mak…