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?
Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don't need to specify the type of the value that you input thus making it more flexible to use. The '=>' is the lambda operator which is used in all lambda expressions.
the operator => has nothing to do with linq - it's a lambda expression. It's used to create anonymous functions, so you don't need to create a full function for every small thing.
In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With