Reputation: 2160
I'm coding my way through the MS 101 Linq tutorial.
I try to refactor query to lambda/method syntax (and vice-versa). This one is a challenge for me.
The given query is:
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 };
Which I re-wrote like this:
var custSupQuery = suppliers.Join(customers, s => s.Country, c => c.Country, (c, s) => new { Key = s.Country, Items = s, Items2 = c });
(I didn't see an easy way to combine the fields form both types in the new clause, so I left them separate).
This seems to fly with the compiler until it gets to the display loops. The 2nd foreach can't seem to handle the type.
Here is the display code (which works with the query expression but not with the lambda/method syntax):
foreach (var item in custSupQuery)
{
Console.WriteLine(item.Key + ":");
foreach (var element in item.Items) // <-- error here
{
Console.WriteLine(" " + element.CompanyName);
}
}
The error is:
foreach statement cannot operate on variables of type 'JoinOperators.Program.Customer' because 'JoinOperators.Program.Customer' does not contain a public definition for 'GetEnumerator'
I tried ending my lambda/query syntax with an AsEnumerable()
call, but it still gets the same error. I'm not sure what I could use as the type in the AsEnumerator<type_goes_here>
since it's anonymous and I don't seem to have an object I could call GetType()
on.
Any suggestions?
Upvotes: 5
Views: 2079
Reputation: 174477
The join ... into
syntax isn't equivalent to Join
but to GroupJoin
. That's what you have to use:
var custSupQuery =
suppliers.GroupJoin(customers, s => s.Country, c => c.Country,
(s, cs) => new { Key = s.Country, Items = cs });
Upvotes: 5