LINQ (Language Integrated Query) is a tool in C# that allows you to perform queries on data collections in a declarative way. One of the most common and useful operations in LINQ is data grouping, a fundamental feature when you need to organize and summarize records according to certain keys.
What is grouping in LINQ?
Grouping in LINQ is the process of organizing the elements of a collection into groups based on a specific key. It is similar to the “GROUP BY” concept in SQL. The result of grouping is a collection of groups, where each group contains a key and a collection of items that share that key.
Basic structure of grouping
The basic structure of grouping in LINQ uses the GroupBy method, which groups the elements of a collection based on a key provided by a projection function. Its syntax is as follows:
var result = collection.GroupBy(element => element.Key);
Here, collection is the original data collection, and in the lambda expression element => element.Key, we are saying that the key for grouping is the Key property of each element. In other words, for each element in the collection, GroupBy uses the value of the Key property to determine which group the element should belong to.
Grouping products by category
To understand how grouping works in LINQ, let’s work with a simple example that uses a list of products. First, we need to define our product entity. In C#, this is done by creating a class that represents what we want to store. In our case, we’ll create a class called Product that has three properties: Name, Category, and Price.
public class Product
{
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Next, we create a list of Product objects, each with specific values for those properties, such as different categories and prices.
List products = new List
{
new Product { Name = "Television", Category = "Electronics", Price = 1900 },
new Product { Name = "Sofa", Category = "Furniture", Price = 1200 },
new Product { Name = "Dining Table", Category = "Furniture", Price = 900 },
new Product { Name = "Notebook", Category = "Electronics", Price = 2500 },
new Product { Name = "Hose", Category = "Gardening", Price = 35 }
};
Now, we want to group these products by category. To do that, we use the GroupBy method to organize the products into groups where each group has a specific key. In this case, the key will be the product’s Category.
var groupByCategory = products.GroupBy(p => p.Category);
The result is a collection of groups, where each group contains products that belong to the same category. That is, a group with the key “Electronics” will contain “Television” and “Notebook”, a group with the key “Furniture” will contain “Dining Table” and “Sofa”, and a third group with the key “Gardening” will contain the item “Hose”.
To display the products grouped by category, we iterate through each group. Within each group, we use the Key property to get the category and access all products in that category.
foreach (var group in groupByCategory)
{
Console.WriteLine($"Category: {group.Key}");
foreach (var product in group)
{
Console.WriteLine($"- {product.Name}: {product.Price:C}");
}
}
During this iteration, the Key property of each group gives us the category of the group, and the collection contains all the products that belong to that category. Finally, we display each group of products, showing the name and price of each item within the corresponding category.
The output would be something like this:
Category: Electronics
- Television: $1,900.00
- Notebook: $2,500.00
Category: Furniture
- Sofa: $1,200.00
- Dining Table: $900.00
Category: Gardening
- Hose: $35.00
This clearly shows how the products were grouped by category and displays each product within its corresponding category. From there, you can perform different operations on the groups, such as applying aggregation functions to obtain totals for each dataset.
Conclusion
Grouping in LINQ is a powerful tool for organizing and summarizing data. Using the GroupBy method, you can group elements based on a specific key and apply aggregation operations to gain further insights. In C#, LINQ makes these operations intuitive and easy to read, enabling more declarative and expressive queries.