Linq全外连接

时间:2017-01-25 12:26:33

标签: c# entity-framework linq linq-to-sql

嗨,大家好我试图从2张表中获得完整的外部联接

EX:

Table_A 
--------
_a
_c

Table_B
------
_a
_b

结果应为

Table_C
-------
_a
_b
_c

但我似乎没有得到实际结果

这就是我所做的

IEnumerable<string> leftOuter1 = (from watcher in _watchers
                                     join attendee in attendees on watcher equals attendee into set
                                     from attendee in set.DefaultIfEmpty()
                                     select attendee);

    IEnumerable<string> rightOuter1 = (from attendee in attendees
                                       join watcher in _watchers on attendee equals watcher into set
                                      from watcher in set.DefaultIfEmpty()
                                      select watcher);


    IEnumerable<string> participants1 = leftOuter.Union(rightOuter);

在_watchers中我有价值&#34; _a&#34;。

参与者的价值观&#34; _a&#34;和&#34; _b&#34;。

第一个结果是_a,但第二个是_a,null。我在这做错了什么?

谢谢

1 个答案:

答案 0 :(得分:1)

你可以看到这个

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

请参阅LINQ - Full Outer Join