2014-01-10 46 views
0

,我有以下數據:如何執行左外連接具有鮮明的條款

用戶

Id UserId Name 
---------------- 
1 1  Him 
2 10  Her 
3 2  Other 

Id GroupId UserId 
------------------- 
1 1  1 
2 2  2 
3 3  10 

在SQL我可以做些什麼像這樣來確定用戶是否在任何組

select * 
from Users as u 
left outer join (select distinct(UserId) from Groups) as g on u.UserId = g.UserId 

結果應該是這樣的。

Id UserId Name UserId 
------------------------ 
1 1  Him 1 
2 10  Her 10 
3 2  Other Null 

但我怎麼能在LINQ中做到這一點?

+0

一個「用戶ID」通常是本質上是不同的值,你可能甚至不需要明確的條款 – Alex

回答

1

我覺得這個人是ü有幫助的,

var data = (from u in Users 
        join g in Groups.Where(a => a.UserId == (from gp in Groups.Select(r=>r.UserId).Distinct())) 
        on u.UserId equals g.UserId into outer 
        from x in outer.DefaultIfEmpty() 
        select u); 
0

在函數的語法,它看起來像

var result = Users.Join(Groups, 
    U => U.UserId, G => G.GroupId, 
    (U,R) => R.Select(
     G => new { Id = U.Id, UserId = U.UserId, Name = U.Name, UserId = G.UserId } 
     ).DefaultIfEmpty(new { Id = U.Id, UserId = U.UserId, Name = U.Name, UserId = null }) 
    ); 
+0

謝謝你的回答 – user2472565