LINQ
Group By
Multiple Columns
C# Programming
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

Sure, here's a detailed article on how to group by multiple columns using LINQ:


LINQ (Language Integrated Query) is a powerful feature in .NET, allowing developers to write queries for data manipulation and retrieval directly within C# or VB.NET code. One common task in data processing is grouping data by multiple columns. This article dives into how you can achieve that using LINQ, providing technical explanations and examples to illustrate the concept.

Understanding Grouping in LINQ

Grouping operations in LINQ are analogous to the SQL GROUP BY clause. The GroupBy method in LINQ can be used to group elements of a sequence based on one or more key values extracted from the elements.

Basic Syntax

The general syntax for GroupBy in LINQ is as follows:

csharp
var groupedResult = collection.GroupBy(keySelectorFunc);

Where collection is the IEnumerable to group, and keySelectorFunc is a function to extract the key for each element.

Grouping by Multiple Columns

To group by multiple columns, you essentially use an anonymous type to represent the composite key. Here's how it's done:

csharp
var groupedResult = collection.GroupBy(item => new { item.Column1, item.Column2 });

Example: Grouping by Multiple Columns

Consider a collection of Person objects where you want to group by Country and City:

csharp
1public class Person
2{
3    public string Name { get; set; }
4    public string Country { get; set; }
5    public string City { get; set; }
6}
7
8var people = new List<Person>
9{
10    new Person { Name = "John", Country = "USA", City = "New York"},
11    new Person { Name = "Anna", Country = "USA", City = "Boston"},
12    new Person { Name = "Mike", Country = "Canada", City = "Toronto"},
13    new Person { Name = "Sophia", Country = "Canada", City = "Vancouver"},
14    new Person { Name = "Lucas", Country = "USA", City = "New York"}
15};
16
17var groupedByCountryCity = people
18    .GroupBy(p => new { p.Country, p.City })
19    .Select(g => new 
20    {
21        Key = g.Key,
22        People = g.ToList()
23    });
24
25foreach (var group in groupedByCountryCity)
26{
27    Console.WriteLine($"Country: {group.Key.Country}, City: {group.Key.City}");
28    foreach (var person in group.People)
29    {
30        Console.WriteLine($"  - {person.Name}");
31    }
32}

Explanation of the Process

  1. Anonymous Type Key: When grouping by multiple columns, we create an anonymous type &#123; p.Country, p.City &#125; to hold the group keys.
  2. Iteration Over Groups: The result of a GroupBy operation is an IEnumerable of groups. Each group contains a key and a collection of items.
  3. Projection with Select: The Select statement projects each group into a new type that includes the key and the list of people in that group.

Advantages of Grouping by Multiple Columns in LINQ

  • Code Clarity: Using LINQ for grouping operations makes the code more readable and concise.
  • Directly Integrated: Being part of the language, LINQ allows compile-time checks and IntelliSense support.
  • Flexibility: LINQ can be used over in-memory collections as well as database queries through LINQ to SQL or Entity Framework.

Use Cases

  • Data Analysis: Aggregate sales data by year and quarter.
  • Report Generation: Group log entries by severity and date.
  • Inventory Sorting: Organize product catalogs by category and supplier.

Summary Table

Here is a concise summary of key points regarding grouping by multiple columns in LINQ:

FeatureDetails
Anonymous Type KeysCombine multiple columns into a single grouping key using anonymous types.
IntegrationUse with LINQ to Objects, LINQ to SQL, and Entity Framework.
SyntaxGroupBy(item => new &#123; item.Column1, item.Column2 &#125;)
FlexibilityEasily extendable with additional methods like Select, OrderBy.
Use CasesData analytics, reporting, inventory management.

Conclusion

Grouping by multiple columns using LINQ is a straightforward yet powerful technique. It not only simplifies the querying process but also maintains a clean and readable codebase. Whether working with in-memory collections or querying a database, LINQ provides a seamless approach to data grouping tasks in .NET applications.



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.