2017-05-14 63 views
2

我发现这个代码在LINQ - Full Outer Join实现差异连接和右外连接在LINQ

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

包含此代码的答案有很多upvotes的,但我在这里观察了什么。在左外连接中,它使用intofrom与第二个实体,在右外连接中执行相同操作。所以,这两个实现对我来说都是一样的。你能告诉我左外连接和右外连接的区别吗?提前致谢。

编辑:

我觉得右外连接应该是这样的:

var rightOuterJoin = from first in firstNames 
        join last in lastNames 
        on first.ID equals last.ID 
        into temp 
        from first in temp.DefaultIfEmpty(new { last.ID, Name = default(string) }) 
        select new 
        { 
         last.ID, 
         FirstName = first.Name, 
         LastName = last.Name, 
        }; 
+0

它在这个网站也是一样的:http://www.dotnetfunda.com/codes/show/1849/how-to-use-left-right-outer-join-in-linq我真的看不到不同的是:( – jason

+1

我不明白这个问题,你把左边的东西变成正确的东西是你交换左边和右边的东西,这是在这里做了什么,你为什么认为这是错误的? –

+0

'temp'变量的类型是'IEnumerable '在左连接中,但是在右边的'IEnumerable '类型,所以有差别。 – Evk

回答

1

下面是不同类型的连接的可视化解释。

Visual Representation of Joins

的主要区别是,LEFT将保留所有记录,从第1表(或左表),而RIGHT将保留所有记录,从第2表。

即使在记录中找到NULL值,OUTER也会返回行。

+0

是的,我知道这个图表,但这并不能回答我的问题。实施**?上面的代码是否正确,如果是,如何?如果没有如何? – jason