有可能从linq查询中获得左连接列表吗?

本文关键字:连接 列表 linq 查询 有可能 | 更新日期: 2023-09-27 18:18:33

假设我有这样的参考设置

public class Account
{
    Guid ID {get;set;}
    string name {get;set}
}
public class Order
{
    Guid ID {get;set;}
}
public class AccountOrder
{
    Guid ID {get;set}
    Guid AccountID {get;set}
    Guid OrderID {get;set}
}
Now when I want to model this setup as so:
public class AccountOrderModel
{
    //One account with many orders 
    string name {get;set}
    List<Order>orders {get;set;}
}

我想使用Linq获得基于帐户订单引用的所有订单的1帐户。

有可能从linq查询中获得左连接列表吗?

我以前发布的代码不是一个正确的左外连接…如果没有关联的订单,它将不会返回一个帐户。

        var aom = from a in accounts
                  join ao in accountorders on a.ID equals ao.AccountID into aoGroup
                  from aod in aoGroup.DefaultIfEmpty(new AccountOrder())
                  join o in orders on aod.OrderID equals o.ID into oGroup
                  group oGroup by a into g
                  select new AccountOrderModel() { Name = g.Key.Name, orders = g.SelectMany(x => x).ToList() };

我已经测试过了,我想我终于得到了正确的答案。