如何使用distinct子句执行左外连接

时间:2014-01-10 12:35:29

标签: linq-to-sql

我有以下数据:

用户

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中做到这一点?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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 })
    );