如何将此SQL外部联接转换为LINQ

时间:2017-08-24 03:40:19

标签: sql linq

我想将其转换为Linq:

SELECT      {fields}
FROM        tableA AS A
LEFT JOIN   tableB AS B
ON             B.Field1 = MyVariable
AND            (    A.Key = B.Key
               OR   A.Key = B.AlternateKey)

正是OR与AND子句一起使我绊倒了。

编辑:我可以将解决方案作为扩展方法吗。

1 个答案:

答案 0 :(得分:1)

from a in tableA
  from b in tableB.Where(b => b.Field1 == MyVariable && (a.Key == b.Key || a.Key == b.AlternateKey)).DefaultIfEmpty()
  select new { a, b };

tableA.SelectMany(
  a => tableB.Where(b => b.Field1 == MyVariable && (a.Key == b.Key || a.Key == b.AlternateKey)).DefaultIfEmpty()
  .Select(b => new { a, b })
  );