I stumbled across this code today and realized I don't understand it what-so-ever.
someArray.Select((x, i) => new XElement("entry",
new XElement("field", new XAttribute("name", "Option"), i + 1)
What is the point of (x, i)? I see a reference to the i, but I'm not understanding how the x fits into this lamda expression.
Also, why is i an integer? I see towards the end there is an i + 1, so I'm assuming that's true.
Thanks for your help
The x is the value, and the i is the index.
For example, the snippet:
void Main()
{
var values = new List<int> {100, 200, 300};
foreach( var v in values.Select((x, i) => (x, i))) // x is the value, i is the index
Console.WriteLine(v);
}
prints out:
(100, 0) (200, 1) (300, 2)
The Microsoft documentation is here
It's there because the expression wanted to use the index of the element, which is the second parameter of the lambda expression, i. The other overload of Select, the one in which the Function object passed accepts just one argument, accesses only the element, (lambda parameter named x in that example).
Here's a link to the Select method documentation.
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