LINQ左外连接语法差异

时间:2011-07-22 13:40:46

标签: c# linq join linq-to-objects left-join

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

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

我找到了很多First Way的例子(使用'into'),这就是我以前做LEFT OUTER JOINS的方式。最近我找到了第二种方式,看起来更简单。我测试了,它们都产生了相同的结果。现在我的问题是存在任何隐藏的差异,表现,还是仅仅是语法糖?

非常感谢。

1 个答案:

答案 0 :(得分:6)

如果您不使用!= null检查

,则应使用第一种方法

左外连接选择左表中的所有内容以及右表中匹配的所有项,如果右表中不存在匹配,则仍返回结果,但右表中的值为null(linq转换为此作为集合项类型的默认值)

您的查询都有效地执行内部联接,因此它们将是相同的。

获得不同的结果

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