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:
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:
Things to watch
- Performance: grouping can be expensive on large datasets with several key columns. Measure, and optimize data indexing and queries where needed.
- Readability: multi-column grouping adds complexity. Use well-named variables and extract methods to keep it maintainable.
- 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.
| Aspect | Detail |
| Method | Use GroupBy with anonymous types for clarity and built-in equality handling. |
| Aggregation | Post-grouping operations include sum, average, count, etc. |
| Performance | Consider performance impacts; grouping can be computationally intensive. |
| Complexity | Multi-column grouping increases complexity; keep code maintainable. |
Related reading
- How to handle AccessViolationException
- How to handle async Start errors in TopShelf
- How to handle click event in Button Column in Datagridview?
- How to handle Task.Run Exception
- How to hide public methods from IntelliSense
- How to identify if the DLL is Debug or Release build in .NET
- How to implement cancellation in Request Reply Pattern in .NET?
- How to implement Oplock opportunistic locking in .NET?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData 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.