问题
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
回答1:
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
回答2:
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.
回答3:
You are looking at this particular overload of LINQ .Select() method. As mentioned above, i is just an (zero-based*) index of respective x in the sequence.
Coming back to your particular code snippet, it completely disregards x and uses i to generate a (one-based) value that ends up translating into an XML node. So if you, say, have your
var someArray = Enumerable.Range(9999,5); // I'm just generating some big numbers here, you can do the same with strings or objects - it doesn't matter.
and run the code you will get something like this:
<entry>
<field name="Option">1</field>
</entry>
<entry>
<field name="Option">2</field>
</entry>
<entry>
<field name="Option">3</field>
</entry>
<entry>
<field name="Option">4</field>
</entry>
<entry>
<field name="Option">5</field>
</entry>
来源:https://stackoverflow.com/questions/59258472/linq-what-does-x-i-do