2013-02-20 65 views
5

我正在编写通过MS 101 Linq教程的方法。linq使用lambda语法加入运算符类型

我尝试将查询重构为lambda/method语法(反之亦然)。 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似乎无法处理这种类型。

这里是显示代码(其与查询表达式,但不与拉姆达/方法的语法作品):

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

错误是:

foreach语句不能在变量操作键入 'JoinOperators.Program.Customer',因为 'JoinOperators.Program.Customer'不包含公共定义 'GetEnumerator'

我试图用AsEnumerable()调用结束我的lambda/query语法,但它仍然得到相同的错误。我不确定我可以在AsEnumerator<type_goes_here>中使用哪种类型,因为它是匿名的,我似乎没有可以调用GetType()的对象。

有什么建议吗?

+2

s只是一件事,而不是一个东西的集合。 – 2013-02-20 14:49:25

回答

5

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

var custSupQuery = 
    suppliers.GroupJoin(customers, s => s.Country, c => c.Country, 
         (s, cs) => new { Key = s.Country, Items = cs }); 
+0

谢谢!当我在http://georgewashingtoncsharp.wordpress.com/上发布这篇文章时,我会给你留言。 – micahhoover 2013-02-20 15:00:08