Is there a Linq function that returns indices?
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
.
精彩评论