mpen
mpen

Reputation: 283143

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 above each foreach.

Upvotes: 2

Views: 85

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063724

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.

Upvotes: 6

Related Questions