gpt4 book ai didi

c# - LINQ 左外连接语法差异

转载 作者:行者123 更新时间:2023-12-02 15:33:14 25 4
gpt4 key购买 nike

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

我发现了很多第一种方式的例子(使用“into”),这就是我用来做左外连接的方式。最近发现了第二种方法,看起来更简单。我测试过,它们都产生相同的结果。现在我的问题是有什么隐藏的差异、性能,还是只是语法糖?

非常感谢。

最佳答案

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

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

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

获得不同的结果

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

关于c# - LINQ 左外连接语法差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6790868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com