Linq to sql 如何使用distinct子句执行左外部联接

Linq to sql 如何使用distinct子句执行左外部联接,linq-to-sql,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 组: Id UserId Name ---------------- 1 1 Him 2 10 H

我有以下数据:

用户

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

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

我认为这一点对你很有帮助

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);

在函数语法中,它看起来像

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 })
    );

“UserId”通常本质上是一个不同的值,您甚至不需要使用不同的子句来回答这个问题