灵巧;如何在多个条件下执行左外连接?

Posted

技术标签:

【中文标题】灵巧;如何在多个条件下执行左外连接?【英文标题】:LINQ; How to perform left outer join with multiple conditions? 【发布时间】:2013-04-19 12:53:44 【问题描述】:

我在模仿:

DB1 AS A LEFT OUTER JOIN
DB2 AS B 
ON A.[Currency Code] = B.[Currency Code] 
AND A.[Document Date] >= B.[Starting Date] 
AND A.[Document Date] <= B.[Ending Date]

这就是我现在拥有的:

from ledgers in ledgerEntries
join currency in currencyExchange
    on ledgers.CurrencyCode equals currency.CurrencyCode
        into c
from currencies in c.DefaultIfEmpty()
where
    ledgers.DocumentDate >= currencies.StartingDate
    && ledgers.DocumentDate <= currencies.EndingDate

我读过有关创建匿名类型并将它们设置为彼此相等的信息,但是当使用小于和大于比较日期时,这不起作用。

【问题讨论】:

【参考方案1】:

看来this 的答案正是我想要的。

from ledgers in ledgerEntries
join currency in currencyExchange
    on ledgers.CurrencyCode equals currency.CurrencyCode
        into c
from currencies in c.Where(currency => currency.StartingDate <= ledgers.DocumentDate 
&& currency.EndingDate <= ledgers.DocumentDate).DefaultIfEmpty()

结合this的回答,我可以简化为:

from ledgers in ledgerEntries
from currencies in currencyExchange.Where(
    currency => currency.CurrencyCode == ledgers.CurrencyCode
    && currency.StartingDate <= ledgers.DocumentDate 
    && currency.EndingDate <= ledgers.DocumentDate).DefaultIfEmpty()

【讨论】:

以上是关于灵巧;如何在多个条件下执行左外连接?的主要内容,如果未能解决你的问题,请参考以下文章

左外连接导轨在 where 条件下具有急切加载

带条件sql的左外连接

Linq to Sql:多个左外连接

django中带有额外条件的左外连接

如何在 Linq 中执行左外连接? [复制]

Linq表达式多个左外连接错误