Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - What does (x, i) do?

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

like image 611
Kellen Stuart Avatar asked Jan 25 '23 12:01

Kellen Stuart


2 Answers

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

like image 119
Phillip Ngan Avatar answered Jan 28 '23 15:01

Phillip Ngan


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.

like image 30
Davi Avatar answered Jan 28 '23 15:01

Davi