Search code examples
.netienumerable

Is there an equivalent to Python's enumerate() for .NET IEnumerable


I could not find a related question.

In python you can easily loop through a sequence (list, generator etc) and collect the index of the iteration at the same time thanks to enumerate(seq) like this :

>>> for (i,item) in enumerate(["toto","titi","tutu"]):
...     print i, item
...
0 toto
1 titi
2 tutu

Is there something similar for IEnumerable, that would, for instance, transform a IEnumerable<T> in a IEnumerable<Tuple<Int32,T>> ?

(I know it would be easily done thanks to the correct function in Select() .. but if it exists, I'd rather use it :) )

UPDATE FYI, I am curious about this kind of possibility to be able to do something like : "give me the index of the last item that fulfils this condition", which would then be accomplished through :

myEnumeration.First(t => some condition on t.Item2 ... ).Item1;

Solution

  • Instead of using a Tuple<,> (which is a class) you can use a KeyValuePair<,> which is a struct. This will avoid memory allocations when enumerated (not that they are very expensive, but still).

    public static IEnumerable<KeyValuePair<int, T>> Enumerate<T>(this IEnumerable<T> items) {
        return items.Select((item, key) => new KeyValuePair(key, item));
    }