LINQ
Group By
Programming
C# .NET
Query Syntax

Group by in LINQ

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction to LINQ and Group By

Language Integrated Query (LINQ) is a powerful feature of the .NET framework that provides a consistent way to query various data sources such as databases, XML documents, and even in-memory collections like lists and arrays. One of the fundamental concepts in LINQ is the ability to group collections of data by a common key using the GroupBy method. This functionality allows developers to easily categorize and summarize data, which comes in handy especially when dealing with complex data structures.

Understanding GroupBy

In LINQ, GroupBy is used to categorize items in a collection into a new sequence of groups based on a specified key or condition. Each group is represented by IGrouping<TKey, TElement>, where TKey is the type of the key on which the grouping is performed, and TElement is the type of the items in the original collection.

Syntax of GroupBy

There are several overloads of the GroupBy method, but the most commonly used syntax is:

csharp
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector);

Here:

  • TSource is the type of the elements in the source sequence.
  • TKey is the type used to group the elements in the collection.
  • keySelector is a function to extract the key for each element.

Example Usage

Consider a simple example where we have a list of products, and we want to group them by their category:

csharp
1public class Product
2{
3    public string Name { get; set; }
4    public string Category { get; set; }
5    public decimal Price { get; set; }
6}
7
8List<Product> products = new List<Product>
9{
10    new Product { Name = "Apple", Category = "Fruit", Price = 1.50M },
11    new Product { Name = "Banana", Category = "Fruit", Price = 0.50M },
12    new Product { Name = "Cucumber", Category = "Vegetable", Price = 1.20M }
13};
14
15var groupedProducts = products.GroupBy(p => p.Category);
16
17foreach (var group in groupedProducts)
18{
19    Console.WriteLine($"Category: {group.Key}");
20    foreach(Product product in group)
21    {
22        Console.WriteLine($" - {product.Name}: ${product.Price}");
23    }
24}

Aggregation with GroupBy

GroupBy becomes particularly powerful when combined with aggregation functions like Count, Sum, Max, etc. For example, if you want to find the total price of products in each category, you might do:

csharp
1var categoryTotals = products.GroupBy(p => p.Category)
2                             .Select(g => new { Category = g.Key, TotalPrice = g.Sum(p => p.Price) });
3
4foreach(var category in categoryTotals)
5{
6    Console.WriteLine($"Category: {category.Category}, Total Price: ${category.TotalPrice}");
7}

Common Use Cases

The GroupBy method is especially useful in scenarios such as:

  • Categorizing data for reporting purposes.
  • Summarizing data to detect patterns.
  • Separating data into logically distinct groups for further analysis.

Summary

PropertyDescription
PurposeOrganize elements into groups based on one or more keys.
ReturnsSequence of IGrouping<TKey, TElement> objects.
Common MethodsCount, Sum, Max, Min, Average
OverloadsMethods supporting result selectors and custom comparers.

Conclusion

The GroupBy method in LINQ is a versatile tool for categorizing and aggregating data. Its simplicity in syntax and the power it brings to data manipulation make it an essential feature for developers working with collections of data in .NET. Whether dealing with financial records, user logs, or any collection-based data structure, GroupBy can help organize and summarize data efficiently and effectively.


Course illustration
Course illustration

All Rights Reserved.