是否有Linq函数返回索引?

时间:2010-11-18 03:57:12

标签: c# linq

基本上,相当于:

public static IEnumerable<KeyValuePair<int, T>> Enumerate<T>(this IEnumerable<T> enumerable)
{
    int i = 0;
    return enumerable.Select(e => new KeyValuePair<int, T>(i++, e));
}

Python有一个,但我在C#中找不到它。如果没有,没有大问题,我只是写了它,但如果它已经存在,我宁愿坚持标准。每个int i=0上方都有一个令人生畏的foreach声明。

1 个答案:

答案 0 :(得分:6)

return enumerable.Select((e, i) => new KeyValuePair<int, T>(i, e));

另请注意,使用i++作为捕获变量的方法并不安全;有人可以先使用Count(),例如使用Parallel

相关问题