C# GroupJoin 多字段关联:示例详解
是的,C# 中的 GroupJoin 方法可以用来将多个字段相互关联。GroupJoin 方法将两个序列的元素进行分组,其中一个序列的元素与另一个序列的元素进行关联。可以根据多个字段来进行关联,只需在关联条件中使用多个字段进行匹配即可。以下是一个示例:
var orders = new List<Order>
{
new Order { OrderId = 1, CustomerId = 1, ProductId = 1, Quantity = 10 },
new Order { OrderId = 2, CustomerId = 1, ProductId = 2, Quantity = 5 },
new Order { OrderId = 3, CustomerId = 2, ProductId = 1, Quantity = 3 },
new Order { OrderId = 4, CustomerId = 2, ProductId = 2, Quantity = 8 }
};
var customers = new List<Customer>
{
new Customer { CustomerId = 1, Name = 'John' },
new Customer { CustomerId = 2, Name = 'Jane' }
};
var products = new List<Product>
{
new Product { ProductId = 1, Name = 'Product 1' },
new Product { ProductId = 2, Name = 'Product 2' }
};
var result = customers.GroupJoin(
orders,
customer => customer.CustomerId,
order => order.CustomerId,
(customer, customerOrders) => new
{
Customer = customer,
Orders = customerOrders.Join(
products,
order => order.ProductId,
product => product.ProductId,
(order, product) => new { Order = order, Product = product }
)
}
);
foreach (var customer in result)
{
Console.WriteLine($'Customer: {customer.Customer.Name}');
foreach (var order in customer.Orders)
{
Console.WriteLine($'Order: {order.Order.OrderId}, Product: {order.Product.Name}, Quantity: {order.Order.Quantity}');
}
}
以上示例中,我们将顾客、订单和产品进行关联。通过 GroupJoin 方法,我们首先将顾客和订单按照 CustomerId 字段进行关联,然后通过 Join 方法将订单和产品按照 ProductId 字段进行关联。最后,我们可以通过遍历结果来获取关联后的数据。
原文地址: https://www.cveoy.top/t/topic/pplM 著作权归作者所有。请勿转载和采集!