c# - LINQ中左外连接和右外连接的实现区别

标签 c# linq join

我在 LINQ - Full Outer Join 找到了这段代码:

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

包含这段代码的答案得到了很多赞成票,但我发现这里有些问题。在左外连接中,它对第二个实体使用 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,
                     };

最佳答案

这是对不同类型联接的直观解释。

Visual Representation of Joins

主要区别在于LEFT 将保留第一个表(或左表)中的所有记录,而RIGHT 将保留第二个表中的所有记录。

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

关于c# - LINQ中左外连接和右外连接的实现区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966023/

相关文章:

c# - 用于在C#中检查有效属性名称的正则表达式

c# - 使用本地数据库发布 WPF 应用程序

c# - 为什么这个 LINQ 查询没有按预期工作?

mysql - 合并数据库查询

mysql - 何时为 MySQL (SQL) 使用 JOIN

c# - 为什么要使用 Double-Checked Locking?

c# - 在 IIS Express 上调试 ASP.NET 时出现重复请求

python - 将解析后的 pdf 中的句子连接在一起

c# - LINQ 和字典线程安全

asp.net - 显示带有嵌套 ListViews 的 IGrouping<>