linq连接运算符类型与lambda语法

mic*_*ver 5 c# linq

我正在通过MS 101 Linq教程编写代码.

我尝试重构查询lambda /方法语法(反之亦然).对我来说是一个挑战.

给定的查询是:

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 };
Run Code Online (Sandbox Code Playgroud)

我改写的是这样的:

var custSupQuery = suppliers.Join(customers, s => s.Country, c => c.Country, (c, s) => new { Key = s.Country, Items = s, Items2 = c });
Run Code Online (Sandbox Code Playgroud)

(我没有看到在新子句中将这些字段组合成两种类型的简单方法,因此我将它们分开).

这似乎与编译器一起飞行,直到它到达显示循环.第二个foreach似乎无法处理这种类型.

这是显示代码(使用查询表达式但不使用lambda /方法语法):

foreach (var item in custSupQuery)
{
    Console.WriteLine(item.Key + ":");
    foreach (var element in item.Items)  // <-- error here
    {
        Console.WriteLine("   " + element.CompanyName);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

foreach语句不能对"JoinOperators.Program.Customer"类型的变量进行操作,因为"JoinOperators.Program.Customer"不包含"GetEnumerator"的公共定义

我尝试通过AsEnumerable()调用结束我的lambda /查询语法,但它仍然得到相同的错误.我不确定我可以使用哪种类型,AsEnumerator<type_goes_here>因为它是匿名的,我似乎没有一个我可以调用的对象GetType().

有什么建议?

Dan*_*rth 5

join ... into语法不等同于Join而是GroupJoin.这是你必须使用的:

var custSupQuery =
    suppliers.GroupJoin(customers, s => s.Country, c => c.Country,
                        (s, cs) => new { Key = s.Country, Items = cs });
Run Code Online (Sandbox Code Playgroud)