2010-11-17 101 views
3

我試圖顯示使用LINQ其他表中不存在的行。誰能幫我?LINQ左連接不等於行

這裏是sql im的使用。

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子句嗎?

回答

9

嗯,你可以做這樣的事情:

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; 

這裏,groupst2行集匹配其「當前」 t1 - 它會如果沒有任何組是空的,這正是你想要的。檢查序列是否爲空的最簡單方法是使用Any方法。

+0

啊......這可能是我想用..很多謝謝瓊.. – seigfred 2010-11-17 07:44:33