Im trying to wrap my head around LINQ statements in C#, Im trying to convert simple queries to the method syntax equivalent.
Most examples i've seen are cluttered with other statements and conditions and use more complex types. For now, i want to keep this as simple as possible. any tips would be appreciated.
// create a list of numbers
List<int> data1 = new List<int>() { 1, 2, 3, 4 };
// create a list of numbers
List<int> data2 = new List<int>() { 5, 6, 7, 8 };
var query = from n1 in data1
from n2 in data2
select n1 * n2;
With this, i get 16 numbers that i can iterate over using a foreach loop. Id like to know how to do the same thing with method syntax.
Thanks.
The full details are in the C# language specification, section 7.16. Additionally, I have an article in my Edulinq blog series which you may find simpler to read.
However, for your particular case... secondary from
calls always end up being converted to SelectMany
calls, so you can start by thinking of this as:
var query = data1.SelectMany(n1 => data2, (n1, n2) => new { n1, n2 })
.Select(pair => pair.n1 * pair.n2);
But actually the compiler will collapse those two because you've just got a select
clause after the from
:
var query = data1.SelectMany(n1 => data2, (n1, n2) => n1 * n2);
It's definitely a good idea to be comfortable with both query expressions and their expansions - I tend to find that when there aren't any transparent identifiers involved (joins, let, etc) then the method syntax is just as easy to read as query expressions, and sometimes simpler - but query expressions simplify things when there are multiple range variables involved.
See more on this question at Stackoverflow