LINQ - (x, i) 做什么? [英] LINQ - What does (x, i) do?

查看:24
本文介绍了LINQ - (x, i) 做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天偶然发现了这段代码,并意识到我根本不理解它.

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)

(x, i) 的重点是什么?我看到对 i 的引用,但我不明白 x 如何适合这个 lamda 表达式.

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.

另外,为什么 i 是一个整数?我看到最后有一个 i + 1,所以我假设这是真的.

Also, why is i an integer? I see towards the end there is an i + 1, so I'm assuming that's true.

感谢您的帮助

推荐答案

x 是值,i 是索引.

例如,片段:

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);
}

打印出来:

(100, 0) (200, 1) (300, 2)

(100, 0) (200, 1) (300, 2)

微软 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆