开发者

Is there a Linq function that returns indices?

开发者 https://www.devze.com 2023-01-26 04:28 出处:网络
Basically, the equivalent of this: public static IEnumerable<KeyValuePair<int, T>> Enumerate<T>(this IEnumerable<T> enumerable)

Basically, the equivalent of this:

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 has one, but I can't find it in C#. If not, no biggie, I just wrote it, but if it already exists, I'd rather stick to the standard. Beats having an akward int i=0 declaration ab开发者_运维问答ove each foreach.


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

Also note that your approach using i++ as a captured variable is not safe; someone could call Count() first, for example - of use Parallel.

0

精彩评论

暂无评论...
验证码 换一张
取 消