LINQ - What does (x, i) do?

我们两清 提交于 2019-12-22 14:48:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!