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 from this blog

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

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2