Group By in C# LINQ
By Tan Lee Published on Jan 20, 2025 138
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
, andPrice
. - Group By: Books are grouped by their
Genre
property using thegroup
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
, andTotalPrice
. - 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
- C# LINQ Tutorial
- C# LINQ query and method syntax
- Group by in LINQ
- How to get the index of an element in C# LINQ
- Cannot use a lambda expression as an argument to a dynamically dispatched operation
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- How to Find XML element by name with XElement in LINQ
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Implementing Caching in ASP.NET Core
Dec 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024