LINQ在不相等的行上左联接 [英] LINQ Left Join On Not Equal Rows
问题描述
我正在尝试使用LINQ显示其他表中不存在的行.有人可以帮我吗?
Im trying to display rows which does not exist from the other table using LINQ. can anyone help me?
这是使用的SQL即时消息.
Here is the sql im using.
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
已经搜索并找到了解决方案.这是我到目前为止所做的.
Already searched and found some solution. Here is what i did so far.
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
上面的代码很好用,但是我只是想知道那是我唯一可以使用的解决方案吗?我的意思是,我们不能直接使用带有where子句的左联接linq而不是使用JOIN和CONTAINS方法吗?
The above code works well but im just wondering if that is the only solution i can use? I mean, instead of using JOIN and CONTAINS method, can't we use left join linq directly with a where clause?
推荐答案
好,您可以执行以下操作:
Well, you could do something like this:
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
方法.
Here, groups
is the set of rows in t2
which match the "current" t1
- it will be empty if there aren't any groups, which is exactly what you want. The easiest way of checking whether a sequence is empty is to use the Any
method.
这篇关于LINQ在不相等的行上左联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!