gpt4 book ai didi

c# - Linq SelectMany

转载 作者:行者123 更新时间:2023-11-30 13:47:52 26 4
gpt4 key购买 nike

您好,我正在通过 MS 101 linq 示例编写代码。

“JoinOperators”给我带来了困难,因为我试图将查询表达式重构为 lambda 语法,反之亦然。

无论如何,在例子105我看到这个查询表达式:

var supplierCusts =
from sup in suppliers
join cust in customers on sup.Country equals cust.Country into cs
from c in cs.DefaultIfEmpty() // DefaultIfEmpty preserves left-hand elements that have no matches on the right side
orderby sup.SupplierName
select new
{
Country = sup.Country,
CompanyName = c == null ? "(No customers)" : c.CompanyName,
SupplierName = sup.SupplierName
};

我尝试以这种方式将其实现为 lambda:

// something is not right here because the result keeps a lot of "Join By" stuff in the output below
var supplierCusts =
suppliers.GroupJoin(customers, s => s.Country, c => c.Country, (s, c) => new { Customers = customers, Suppliers = suppliers })
.OrderBy(i => i.Suppliers) // can't reference the "name" field here?
.SelectMany(x => x.Customers.DefaultIfEmpty(), (x, p) => // does the DefaultIfEmpty go here?
new
{
Country = p.Country,
CompanyName = x == null ? "(No customers)" : p.CompanyName,
SupplierName = p // not right: JoinOperators.Program+Customer ... how do I get to supplier level?
});

出于某种原因,我无法通过这种方式访问​​供应商级别的信息。当我将 customers 切换到 suppliers 时,我无法访问客户级别的信息。

是否有一些 SelectMany() 的重载让我从两个对象的字段级中提取?

另外,我不明白为什么 GroupJoin() 似乎返回一个包含 2 个集合(supplierscustomers)的对象。难道不应该以某种方式加入他们吗?

我想我不明白 GroupJoin() 是如何工作的。

最佳答案

您在群组加入中使用了错误的结果选择器,这就是问题开始的地方。这是固定查询:

var supplierCusts =
suppliers
.GroupJoin(customers,
sup => sup.Country,
cust => cust.Country,
(sup, cs) => new { sup, cs })
.OrderBy(x => x.sup.Name)
.SelectMany(x => x.cs.DefaultIfEmpty(), (x, c) =>
new
{
Country = x.sup.Country,
CompanyName = c == null ? "(No customers)" : c.CompanyName,
SupplierName = x.sup.Name
});

关于c# - Linq SelectMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070665/

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