【问题标题】:LINQ: Left Outer Join with multiple conditionsLINQ:具有多个条件的左外连接
【发布时间】:2012-01-08 13:30:09
【问题描述】:

我有两个 IEnumerable,分别称为 BaseReportDefinitions 和 InputReportDefinitions。我需要在我想要所有 InputReportDefinitions 和任何匹配的 BaseReportDefinitions 的地方进行左外连接。两个 IEnumberable 都包含 ReportDefinition 对象,这些对象包含需要用作连接键的 ParentName 和 ReportName 属性。我想为匿名对象中的每个返回 ReportDefinition 对象(在 BaseReportDefinition 条目的情况下,它可能为空)。

我见过很多 linq 外连接和带有静态第二个条件的外连接的例子,这些条件经常被放入 where 条件,但没有真正使用两个条件进行连接。

【问题讨论】:

标签: c# linq outer-join


【解决方案1】:
var items = inputReportDefinitions.GroupJoin(
              baseReportDefinitions,
              firstSelector => new {
                         firstSelector.ParentName, firstSelector.ReportName
                                   },
              secondSelector => new {
                         secondSelector.ParentName, secondSelector.ReportName
                                   },
              (inputReport, baseCollection) => new {inputReport, baseCollection})
              .SelectMany(grp => grp.baseCollection.DefaultIfEmpty(),
                         (col, baseReport) => new
                                                 {
                                                    Base = baseReport,
                                                    Input = col.inputReport
                                                 });

我相信这最终会成为左外连接。我不知道如何将这个怪物转换为查询语句。我认为如果你在末尾添加AsQueryable(),它可以用于Linq-to-SQL,但老实说,我没有这方面的经验。

编辑:我想通了。更容易阅读:

var otherItems = from i in inputReportDefinitions
                         join b in baseReportDefinitions
                         on new {i.ParentName, i.ReportName} 
                         equals new {b.ParentName, b.ReportName} into other
                         from baseReport in other.DefaultIfEmpty()
                         select new
                                    {
                                        Input = i,
                                        Base = baseReport
                                    };

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多