LINQ provides methods to group and aggregate data based on specific properties or conditions.
GroupBy
The GroupBy
method allows you to group elements in a collection based on a key selector function. The result is a collection of groups, each containing elements with the same key value.
Example:
List<Product> products = GetProducts();
var groupedProducts = products.GroupBy(p => p.Category);
foreach (var group in groupedProducts)
{
Console.WriteLine($"Category: {group.Key}");
foreach (var product in group)
{
Console.WriteLine($" Product: {product.Name}");
}
}
GroupJoin
The GroupJoin
method allows you to perform a grouped join between two collections based on a key selector function for each collection.
Example:
List<Customer> customers = GetCustomers();
List<Order> orders = GetOrders();
var customerOrders = customers.GroupJoin(orders,
customer => customer.Id,
order => order.CustomerId,
(customer, orderGroup) => new
{
Customer = customer,
Orders = orderGroup
});
foreach (var item in customerOrders)
{
Console.WriteLine($"Customer: {item.Customer.Name}");
foreach (var order in item.Orders)
{
Console.WriteLine($" Order: {order.Id}");
}
}