我正在通过 MS 101 Linq 教程编写代码。
我尝试将查询重构为 lambda/方法语法(反之亦然)。 This其中一个对我来说是一个挑战。
给定的查询是:
var custSupQuery =
from sup in suppliers
join cust in customers on sup.Country equals cust.Country into cs
select new { Key = sup.Country, Items = cs };
我是这样重写的:
var custSupQuery = suppliers.Join(customers, s => s.Country, c => c.Country, (c, s) => new { Key = s.Country, Items = s, Items2 = c });
(我没有看到在新子句中将两种类型的字段组合起来的简单方法,所以我将它们分开)。
这似乎与编译器一起运行,直到它到达显示循环。第二个 foreach 似乎无法处理该类型。
这是显示代码(它适用于查询表达式,但不适用于 lambda/方法语法):
foreach (var item in custSupQuery)
{
Console.WriteLine(item.Key + ":");
foreach (var element in item.Items) // <-- error here
{
Console.WriteLine(" " + element.CompanyName);
}
}
错误是:
foreach statement cannot operate on variables of type 'JoinOperators.Program.Customer' because 'JoinOperators.Program.Customer' does not contain a public definition for 'GetEnumerator'
我尝试用 AsEnumerable()
结束我的 lambda/查询语法调用,但它仍然得到相同的错误。我不确定我可以将什么用作 AsEnumerator<type_goes_here>
中的类型因为它是匿名的,而且我似乎没有可以调用的对象 GetType()
上。
有什么建议吗?
最佳答案
join ... into
语法不等同于Join
,而是等同于GroupJoin
.这就是你必须使用的:
var custSupQuery =
suppliers.GroupJoin(customers, s => s.Country, c => c.Country,
(s, cs) => new { Key = s.Country, Items = cs });
关于c# - 使用 lambda 语法的 linq 连接运算符类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14982573/