非相等行上的LINQ左连接

非相等行上的LINQ左连接,linq,join,inequality,Linq,Join,Inequality,我正在尝试使用LINQ显示其他表中不存在的行。有人能帮我吗 这是我使用的sql select * from table1 left join table2 on table1.col1 = table2.col1 and table1.col2 = table2.col2 where table2.col1 is null and table2.col2 is null 已经搜索并找到了一些解决方案。以下是我到目前为止所做的 from t1 in table1 where !(fro

我正在尝试使用LINQ显示其他表中不存在的行。有人能帮我吗

这是我使用的sql

select * from table1 
left join table2
on 
table1.col1 = table2.col1 
and 
table1.col2 = table2.col2
where
table2.col1 is null and table2.col2 is null
已经搜索并找到了一些解决方案。以下是我到目前为止所做的

from t1 in table1
where 
!(from t2 in table1
  join t3 in table2 on
  new { t2.col1, t2.col2 } 
  equals 
  new { t3.col1, t3.col2 }
  select t2.PK).Contains(t1.PK)
  select t1

上面的代码运行良好,但我只是想知道这是否是我可以使用的唯一解决方案?我的意思是,不使用JOIN和CONTAINS方法,我们就不能直接使用left-JOIN-linq和where子句吗?

您可以这样做:

var query = from t1 in table1
            join t2 in table2
            on new { t1.col1, t2.col2} equals { t2.col1, t2.col2 }
            into groups
            where !groups.Any()
            select t1;
这里,
groups
t2
中与“当前”
t1
匹配的行集-如果没有任何组,它将为空,这正是您想要的。检查序列是否为空的最简单方法是使用
Any
方法