Linq 中具有不等于谓词的外连接的等价物

Equivalent of outer join with non-equals predicate in Linq

我正在寻找以下 SQL 的 Linq 等价物:

SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
  FROM MyTable t0
  LEFT OUTER JOIN MyTable t1
    ON t0.Fk_CompanyId = t1.Fk_CompanyId AND t0.CheckedUtc < t1.CheckedUtc
 WHERE t1.Fk_CompanyId IS NULL
   AND t0.CheckedUtc IS NOT NULL

我与 Linq 最接近的是:

from t0 in MyTable
join t1 in MyTable on t0.Fk_CompanyId equals t1.Fk_CompanyId into t1tmp
from t1 in t1tmp.DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null && t0.CheckedUtc < t1.CheckedUtc
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }

... 产生以下 SQL(稍微重新格式化):

SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
  FROM MyTable AS t0
  LEFT OUTER JOIN MyTable AS t1
    ON t0.Fk_CompanyId = t1.Fk_CompanyId
 WHERE (t1.Fk_CompanyId IS NULL)
   AND (t0.CheckedUtc IS NOT NULL)
   AND (t0.CheckedUtc < t1.CheckedUtc)

这些并不完全等同。 (t0.CheckedUtc < t1.CheckedUtc 被推送到 WHERE。)当我在 t0.CheckedUtc < t1.CheckedUtc 上进行左外连接时,这会在连接的右侧产生 NULL 值。当我使用 WHERE 过滤时,这将删除我感兴趣的所有 NULL 值。

观点:我正在尝试在 MyTable 中查找具有最新 CheckedUtc 的行,如果有任何非 NULL 行, 按 Fk_CompanyId 分组。我想要每个 Fk_CompanyId 一行。有几个 "possible duplicates" 只处理 查找最近的 CheckedUtcs(而不是它们各自的行),或者假设 CheckedUtc不为空。

所以:如何在 Linq 中对不等于谓词执行等效的联接?

试试这个

from t0 in MyTable
From t1 in MyTable( x=>x.Fk_CompanyId=t0.Fk_CompanyId && x.CheckedUtc > t0.CheckedUtc ).DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null 
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }