假设:
var a = SomeCollection.OrderBy(...)
.Select(f => new MyType
{
counter = ? //I want counter value, so what first
//object have counter=1, second counter=2
//and so on
a=f.sometthing,
...
});
如何设置此计数器值?或者之后我是否愿意迭代a
?
答案 0 :(得分:8)
使用Select的重载,它为您提供当前元素的基于0的索引。
.Select((item, index) => new MyType
{
counter = index + 1,
a = item.Something
答案 1 :(得分:3)
只需捕获一个变量:
int index = 1;
var a = SomeCollection.OrderBy(...)
.Select(x => new MyType { counter = index++; });
计数器将在调用每次迭代时递增。