LINQ
Coding Tips
Programming
.NET Framework
Data Manipulation

How to group by multiple columns using LINQ

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Grouping data is a common need in many software applications, especially while dealing with extensive datasets. Language Integrated Query (LINQ) in .NET provides robust tools to manipulate collections efficiently. One of its powerful capabilities is the ability to group data by multiple columns. This article will explore how to effectively use LINQ to group data by multiple columns, including technical explanations and example code snippets for a clearer understanding.

Understanding GroupBy in LINQ

LINQ's GroupBy method is a powerful feature that allows you to organize your data into groups based on some key that you specify. You can then perform further operations, such as aggregating or filtering, on these groups. When dealing with multiple columns, the procedure involves grouping by a combination of these columns, essentially forming a group key from them.

How to Group By Multiple Columns

To group by multiple columns, you can use anonymous types in C# because they provide a convenient way to bundle multiple pieces of data into a single object. When you use anonymous types, LINQ handles the equality comparisons and hash code generation behind the scenes, based on each property in the anonymous type.

Basic Syntax

Here is a basic example of using GroupBy with multiple columns. Suppose we have a list of products, and each product has a Category, Manufacturer, and Price. The goal is to group the products 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}

Advanced Grouping

Aggregations

After grouping, you often need to perform aggregations like sum, average, or count. Using the group result, you can easily calculate these aggregations.

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}

Considerations When Grouping by Multiple Columns

  1. Performance: Grouping operations can be computationally expensive, especially with large datasets and multiple group keys. It's crucial to measure performance and optimize data indexing and queries appropriately.
  2. Complexity: Multi-column grouping increases complexity. Keep the code readable and maintainable by using well-named variables and method extractions.
  3. Equality and Comparisons: Always ensure that the types you are grouping by have appropriate equality and hash code implementations. This is handled by the anonymous types in C#, but be cautious if using custom types as keys.

Summary

Grouping by multiple columns in LINQ allows for sophisticated data queries and operations, enabling developers to write concise, readable, and powerful data manipulation code using .NET’s integrated query capabilities. Below is a table of key points from this article:

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.

Leverage these insights to use LINQ more effectively in your .NET applications, ensuring that your data processing is both efficient and intelligible.


Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.