是否可以从左侧连接列表中获取linq查询

时间:2013-06-16 17:59:23

标签: c# linq

假设我有这个参考设置

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个帐户。

1 个答案:

答案 0 :(得分:4)

我之前发布的代码不是正确的左外连接..如果没有关联订单,它将无法返回帐户。在此代码中已修复:

        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() };

它已经过测试,我认为我终于弄清楚了。