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.Make, group.Key.Model));
}

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

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4