LINQ左外部JOIN语法差异 [英] LINQ Left Outer JOIN Syntax Difference

查看:103
本文介绍了LINQ左外部JOIN语法差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在LINQ中至少有两种方法可以进行LEFT OUTER JOIN

There are at least two ways of doing LEFT OUTER JOIN in LINQ

class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Order
{
    public int ID { get; set; }
    public string Product { get; set; }
}

    static void Main()
    {
        // Example customers.
        var customers = new Customer[]
        {
            new Customer{ID = 5, Name = "Sam"},
            new Customer{ID = 6, Name = "Dave"},
            new Customer{ID = 7, Name = "Julia"},
            new Customer{ID = 8, Name = "Sue"},
            new Customer{ID = 9, Name = "Joe"}
        };

        // Example orders.
        var orders = new Order[]
        {
            new Order{ID = 5, Product = "Book"},
            new Order{ID = 6, Product = "Game"},
            new Order{ID = 7, Product = "Computer"},
            new Order{ID = 8, Product = "Shirt"},
            new Order{ID = 8, Product = "TShirt"}
        };


        // First Way
        var query = from c in customers
                join o in orders on c.ID equals o.ID into co
                from x in co.DefaultIfEmpty() 
                where x != null && x.Product == "Shirt"
                select new {c, x};

        // Second Way  
        var query2 = from c in customers
                     from o in orders
                     where c.ID == o.ID && o.Product == "Shirt"
                     select new {c, o};
    }

我发现了很多第一种方式"的示例(使用"into"),这就是我以前做过左外连接的方式.最近,我找到了第二种方法,并且看起来更简单.我进行了测试,并且两者都产生了相同的结果.现在我的问题是是否存在任何隐藏的差异,性能,还是仅仅是语法糖?

I found a lot of examples of First Way (using 'into'), and that is the way I used to do my LEFT OUTER JOINS. Recently I found the second way, and looks like it is simpler. I tested and both of them produce the same result. Now my question are there any hidden differences, performance, or it is only syntactic sugar?

非常感谢.

推荐答案

如果不使用!= null检查,则应使用第一种方法

The First way should be used if you don't use the !=null check

左外部联接会从左表中选择所有内容,并在右表中匹配所有项目,如果右表中不存在匹配项,则仍返回结果,但右表中的值将为null(linq将其翻译为作为收集项类型的默认值)

A left outer join selects everything from the left table with all the items that match in the right table, if no matches exist in the right table the result is still returned but null for the values in the right table (linq translates this as the default value for the collection item type)

这两个查询都有效地执行了内部联接,因此它们是相同的.

Both your queries effectively perform an inner join so they will be the same.

获得不同的结果

 // First Way
 var query = from c in customers
 join o in orders on c.ID equals o.ID into co
 from x in co.DefaultIfEmpty()
 where c.Id>5 
 select new {c, x};

 // Second Way
 var query2 = from c in customers
 from o in orders
 where c.ID == o.ID && c.ID > 5
 select new {c, o};

这篇关于LINQ左外部JOIN语法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆