LINQ
Coding Tips
Programming
.NET Framework
Data Manipulation

C# LINQ: group by multiple columns

Codemia Knowledge Hub ·

To group by multiple columns in LINQ, pass an anonymous type as the key: products.GroupBy(p => new { p.Category, p.Manufacturer }). Anonymous types compare equal when all their properties are equal, and LINQ handles the equality checks and hash codes for you, so each distinct combination of values becomes one group.

How GroupBy works with a composite key

GroupBy organizes a collection into groups by a key you specify, and you can then aggregate or filter each group. With several columns, the key is simply a combination of those values. Anonymous types are a convenient way to bundle them into one object.

Example: grouping products by category and manufacturer

Each product has a Category, Manufacturer and Price. This groups by both Category and Manufacturer:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Product
6{
7    public string Category { get; set; }
8    public string Manufacturer { get; set; }
9    public decimal Price { get; set; }
10}
11
12public class Program
13{
14    public static void Main()
15    {
16        List<Product> products = new List<Product>
17        {
18            new Product { Category = "Electronics", Manufacturer = "CompanyA", Price = 300 },
19            new Product { Category = "Electronics", Manufacturer = "CompanyB", Price = 200 },
20            new Product { Category = "Clothing", Manufacturer = "CompanyA", Price = 100 },
21            new Product { Category = "Electronics", Manufacturer = "CompanyA", Price = 150 }
22        };
23
24        var groupedProducts = products.GroupBy(p => new { p.Category, p.Manufacturer });
25
26        foreach (var group in groupedProducts)
27        {
28            Console.WriteLine($"Category: {group.Key.Category}, Manufacturer: {group.Key.Manufacturer}");
29            foreach (var product in group)
30            {
31                Console.WriteLine($" - Price: {product.Price}");
32            }
33        }
34    }
35}

Each group's Key exposes the grouped properties, here group.Key.Category and group.Key.Manufacturer.

Aggregating each group

After grouping you usually want totals, averages or counts. Project each group with Select into a new anonymous type that carries the key values alongside the aggregates, so the result is a flat list you can print or bind directly:

csharp
1var groupedProducts = products
2    .GroupBy(p => new { p.Category, p.Manufacturer })
3    .Select(g => new {
4        g.Key.Category,
5        g.Key.Manufacturer,
6        TotalPrice = g.Sum(p => p.Price),
7        AveragePrice = g.Average(p => p.Price),
8        ProductCount = g.Count()
9    });
10
11foreach (var group in groupedProducts)
12{
13    Console.WriteLine($"Category: {group.Category}, Manufacturer: {group.Manufacturer}");
14    Console.WriteLine($"Total Price: {group.TotalPrice}, Average Price: {group.AveragePrice}, Count: {group.ProductCount}");
15}

Things to watch

  1. Performance: grouping can be expensive on large datasets with several key columns. Measure, and optimize data indexing and queries where needed.
  2. Readability: multi-column grouping adds complexity. Use well-named variables and extract methods to keep it maintainable.
  3. Key equality: the key type must have proper equality and hash code implementations. Anonymous types provide this, but take care if you use a custom type as the key.
AspectDetail
MethodUse GroupBy with anonymous types for clarity and built-in equality handling.
AggregationPost-grouping operations include sum, average, count, etc.
PerformanceConsider performance impacts; grouping can be computationally intensive.
ComplexityMulti-column grouping increases complexity; keep code maintainable.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms