c# - 是否有可能从 linq 查询中获取左连接列表

标签 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 个账户。

最佳答案

我之前发布的代码不是正确的左外连接。如果没有关联的订单,它不会返回一个帐户。在这段已修复的代码中:

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

它已经过测试,我想我终于弄对了。

关于c# - 是否有可能从 linq 查询中获取左连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17136141/

相关文章:

c# - 匹配 2 个字符串的序列

c# - 什么时候调整图像大小?

c# - 如何在连接前获取MAC地址?

asp.net - : LINQ To SQL for data access 的最佳实践

c# - 在给定路径创建 XML 文档

c# - 在 C# Linq 查询中丢弃

.net - CLR 存储过程中数据表上的 LINQ

c# - C# 中的异步方法不是异步的?

c# - 是否可以在 net core 中加载特定于平台的 .net 库?

C#/LINQ 选择具有相同属性的对象的子列表