gpt4 book ai didi

c# - 为什么 LINQ 的连接方式与 SQL 不同?

转载 作者:太空狗 更新时间:2023-10-29 23:19:41 24 4
gpt4 key购买 nike

在 LINQ 中,我可以像这样进行连接:

from c in dc.Customers
join o in dc.Orders on c.custid equals o.custid ...

但是左连接要复杂得多:

from c in dc.Customers 
join o in dc.Orders on c.custid equals o.custid
into temp from x in temp.DefaultIfEmpty() ...

为什么 LINQ 的设计者不能用这样的东西使事情变得简单(更像 SQL)?

from c in dc.Customers
left join o in dc.Orders on c.custid equals o.custid ...

最佳答案

why couldn't the designers of Linq make things simple (more sql like)

他们本来可以。但是您对简单的定义(作为 sql 程序员)与 OO 程序员对简单的定义不同。 Linq(在C#中)首先是面向OO程序员的查询技术。这方面的一个例子是为什么 select 排在最后。这是为了满足 C# 中的作用域规则和编辑器中的智能感知支持。

这些程序员可能不了解 LEFT JOIN(如果您说 LEFT OUTER JOIN 会感到非常困惑 - 认为存在一些差异,就像一个继承自另一个) .

他们真正理解的是 GROUP JOIN,其行为方式类似。

List<int> myInts = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> myOtherInts = new List<int>() { 1, 3, 5, 7, 9, 11, 13 };
//
var query = from i in myInts
join j in myOtherInts on i equals j into g
select new {key = i, myGroup = g};
//
foreach (var grouping in query)
{
Console.WriteLine("--{0}", grouping.key);
foreach (var x in grouping.myGroup)
Console.WriteLine(x);
}

所有 DefaultIfEmpty 所做的就是解压缩组 - 将结果展平为行/列形式 - 远离 OO 程序员的自然层次结构DefaultIfEmpty 在语义上不是获得结果所必需的。

这是方法形式的相同查询 - 编译器从上面生成的,我更喜欢:

var query = myInts.GroupJoin(
myOtherInts,
i => i,
j => j,
(i, g) => new { key = i, myGroup = g }
);

Could you state that in terms of his example?

此查询为您提供客户及其订单作为附加集合。订单集合可能为空。如果您有 50 个客户和 1000 个订单,则结果中将有 50 个客户。

from c in dc.Customers
join o in dc.Orders on c.custid equals o.custid into someOrders
select new CustomerWithOrders()
{theCustomer = c, theOrders = someOrders};

此查询为您提供了 CustomerOrder 行。如果一个客户有 5 个订单,则该客户将出现 5 次,每次都匹配到不同的订单。如果客户有 0 个订单,则一旦匹配到空订单,客户就会出现。如果您有 50 个客户和 1000 个订单,则联接后将有 50-1049 行,结果中元素的含义很难定义。

from c in dc.Customers
join o in dc.Orders on c.custid equals o.custid into temp
from x in temp.DefaultIfEmpty()
select new CustomerOrderHybrid() {theCustomer = c, theOrder = x}

如果他们实现了left join,则需要第二个示例的结果形状。一旦我使用了更好的group join,我也不会一步实现left join。查询结果的层次结构非常好。

关于c# - 为什么 LINQ 的连接方式与 SQL 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/537037/

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