Group By in C# LINQ

By FoxLearn 1/20/2025 3:13:02 AM   9
In C#, LINQ's Group By is a query operator that allows you to organize elements of a sequence into groups based on a specified key selector function.

The key can be an element's property, a computed value, or a custom expression.

The result of the grouping operation is an IEnumerable<IGrouping<TKey, TElement>>, where each group contains a key and a collection of matching elements.

Why Use Group By in LINQ?

Group By can be helpful for tasks such as:

  • Categorizing data based on shared attributes.
  • Performing aggregate operations, such as counting or averaging, on grouped data.
  • Transforming grouped data into new formats for further processing or display.

Here are some examples of when you might use Group By in LINQ:

  • Categorizing books by genre and counting the number of books in each genre.
  • Grouping orders by customer and calculating the total amount spent by each customer.
  • Organizing students by their grade levels and finding the highest score in each group.

How to Group By in C# LINQ

Follow these steps to achieve group by in C# LINQ:

  • Define the data source: Create a collection of objects, such as a list of books or orders.
  • Apply the group keyword: Group the data based on a property, derived value, or custom expression.
  • Use into to create group identifiers: Represent each group with an IGrouping<TKey, TElement> object containing the key and associated elements.
  • Project the results: Use the select keyword to transform the data into the desired output format.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Define the data source
        var books = new List<Book>
        {
            new Book { Id = 1, Title = "C# Basics", Genre = "Programming", Price = 29.99 },
            new Book { Id = 2, Title = "Mastering LINQ", Genre = "Programming", Price = 39.99 },
            new Book { Id = 3, Title = "Cooking 101", Genre = "Cooking", Price = 19.99 },
            new Book { Id = 4, Title = "World History", Genre = "History", Price = 24.99 },
            new Book { Id = 5, Title = "Advanced C#", Genre = "Programming", Price = 49.99 },
            new Book { Id = 6, Title = "Healthy Recipes", Genre = "Cooking", Price = 22.99 }
        };

        // Perform group by using LINQ
        var query = from book in books
                    group book by book.Genre into groupedBooks
                    select new
                    {
                        Genre = groupedBooks.Key,
                        BookCount = groupedBooks.Count(),
                        TotalPrice = groupedBooks.Sum(b => b.Price)
                    };

        // Display the results
        foreach (var result in query)
        {
            Console.WriteLine($"Genre: {result.Genre}");
            Console.WriteLine($"  Number of Books: {result.BookCount}");
            Console.WriteLine($"  Total Price: {result.TotalPrice:C}");
        }

        Console.ReadLine();
    }
}

class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Genre { get; set; }
    public double Price { get; set; }
}

In this example:

  • Data Source: A list of books is created with properties like Id, Title, Genre, and Price.
  • Group By: Books are grouped by their Genre property using the group keyword.
  • Aggregate Operations: Each group calculates the number of books and their total price.
  • Projection: The results are transformed into an anonymous type with Genre, BookCount, and TotalPrice.
  • Display Results: The grouped data is displayed in a formatted manner.

Output: 

Genre: Programming
  Number of Books: 3
  Total Price: $119.97
Genre: Cooking
  Number of Books: 2
  Total Price: $42.98
Genre: History
  Number of Books: 1
  Total Price: $24.99