【问题标题】:Linq Attach Child entity to PArent based on common fieldLinq 根据公共字段将子实体附加到父实体
【发布时间】:2020-11-04 19:41:42
【问题描述】:

我有一个父母和孩子作为单独的对象。现在我必须根据连接条件将两者结合起来。 我的实体是

public class Customer
    {
        private int customerId;
        private string customerName;
        private List<Order> orders;
    }

public class Order
{
    private int customerId;
    private int orderId;
    private string OrderName;
}

这里,customerId 是连接字段。

我有客户列表,但它只有 CustomerId 和 CustomerName 数据。它没有订单(每个客户的订单对象为空) 我有 _orders 作为单独的对象,如下所示。

List<Customer> _customers;
List<Order> _orders;

现在我必须加入两者,最后,我需要 _customers 对象,它也应该有 _orders。

我已使用 foreach 语句将订单附加到每个客户,如下所示。

 _customers.ForEach(c =>
                {
                    c.orders = _orders.Where(o => o.customerId == c.customerId).ToList();
                });

但是,我想排除 foreach 循环并尝试通过连接条件。 有人可以帮忙吗? 提前致谢。

【问题讨论】:

    标签: linq c#-4.0 linq-to-entities


    【解决方案1】:

    您可以使用GroupJoin 来实现:

    List<Customer> result = _customers.GroupJoin(_orders,
        c => c.customerId,
        o => o.customerId,
        (c, o) => new Customer
        {
            customerId = c.customerId,
            customerName = c.customerName,
            orders = o.ToList()
        }).ToList();
    

    在 dotnetfiddle 中测试:https://dotnetfiddle.net/OJN480

    希望对您有所帮助。

    【讨论】:

    • 感谢 Sajid.. 这是完美的
    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 2020-05-31
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多