如何在c#中进行全外连接?

时间:2014-04-03 06:28:44

标签: c# linq join

我是C#中使用Linq方法的新手。我正在学习Join clause,我想我理解所有三种类型的连接,即

  1. 内部联接
  2. 群组加入
  3. 左外连接
  4. 我对Left Outer Join的理解是它返回左源序列的所有元素,无论是否存在正确序列中的匹配元素。

    现在我有一个场景,我想要执行Left Outer Join,并且我还想要Right Source Sequence的所有元素,无论左序列中是否存在匹配元素。

    我该怎么做?

2 个答案:

答案 0 :(得分:2)

你基本上都在询问Full Outer Join。在LINQ中一般使用左右连接和联合在一起。请查看以下主题

Thread 1 Thread 2

示例:

var firstNames = new[]
{
    new { ID = 1, Name = "John" },
    new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
    new { ID = 1, Name = "Doe" },
    new { ID = 3, Name = "Smith" },
};
var leftOuterJoin = from first in firstNames
                    join last in lastNames
                    on first.ID equals last.ID
                    into temp
                    from last in temp.DefaultIfEmpty(new { first.ID, Name = default(string) })
                    select new
                    {
                        first.ID,
                        FirstName = first.Name,
                        LastName = last.Name,
                    };
var rightOuterJoin = from last in lastNames
                     join first in firstNames
                     on last.ID equals first.ID
                     into temp
                     from first in temp.DefaultIfEmpty(new { last.ID, Name = default(string) })
                     select new
                     {
                         last.ID,
                         FirstName = first.Name,
                         LastName = last.Name,
                     };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);

答案 1 :(得分:2)

您需要完整加入,可以left joinright join然后加union,因为在linq to entity中没有full join,例如:

        // left join: left table = TableA, right table = TableB
        var q1 = (from a in TableA
                  join b in TableB on a.ID equals b.ID into JoinedList
                  from b in JoinedList.DefaultIfEmpty()
                  select new
                  {
                      a,
                      b
                  });

        // right join: left table = TableB, right table = TableA
        var q2 = (from b in TableB
                  join a in TableA on b.ID equals a.ID into JoinedList
                  from a in JoinedList.DefaultIfEmpty()
                  select new
                  {
                      a,
                      b
                  });

        var query = q1.Union(q2).ToList();