在LINQ中使用OR条件LEFT JOIN

时间:2014-09-30 10:04:02

标签: c# linq linq-to-sql

我需要在LINQ中编写以下T-SQL:

SELECT T1.ID, T2.Name
FROM T1
LEFT JOIN T2 ON (T1.ID = I2.ID1 OR T1.ID = T2.ID2)

在LINQ中,OR-join看起来像这样:

T1.Join(T2, t1=>new{}, t2=>new{}, (t1,t2)=>new{ID=t1.Id, t2=t2}).Where(o=>o.Id == o.t2.Id1 || o.Id==o.t2.Id2);

但该查询是INNER JOIN,而不是LEFT JOIN。 某种LEFT JOIN看起来像这样:

T1.GroupJoin(T2, t1 => t1.Id, t2 => t2.Id1, (t1, t2) => new { Id = t1.Id, Name1 = t2.Select(t => t.Name) }).DefaultIfEmpty()
  .GroupJoin(T2, o => o.Id, t2 => t2.Id2, (i, j) => new { Id = i.Id, Name1 = i.Name1, Name2 = j.Select(t => t.Name) }).DefaultIfEmpty();

此查询产生正确的结果,但是使用2个连接而不是1.或者它是否真的等同于原始T-SQL?

有人知道如何更好地重写此查询吗?

3 个答案:

答案 0 :(得分:3)

来自类似问题的答案为我们提供了一种编写LEFT JOIN的简便方法: https://stackoverflow.com/a/4739738/1869660

var query = from t1 in T1
            from t2 in T2.Where(tt2 => (t1.ID == tt2.ID1) || (t1.ID = tt2.ID2))
                         .DefaultIfEmpty()
            select new { t1.ID, t2.Name }

答案 1 :(得分:-1)

要使用单个linq解决此问题,请尝试使用交叉连接

var results = (from a in test1
from b in test2
where a.ID == b.ID1 || a.ID == b.ID2
select new {x = a.ID, y = b.Name});

答案 2 :(得分:-2)

var LeftJoin = from emp in ListOfEmployees
               join dept in ListOfDepartment
               on emp.DeptID equals dept.ID into JoinedEmpDept 
               from dept in JoinedEmpDept.DefaultIfEmpty()
               select new                          
               {
                   EmployeeName = emp.Name,
                   DepartmentName = dept != null ? dept.Name : null                          
               };