Is there an equivalent to Python's enumerate() for .NET IEnumerable
C# 7 finally allows you to do this in an elegant way:
static class Extensions
{
public static IEnumerable<(int, T)> Enumerate<T>(
this IEnumerable<T> input,
int start = 0
)
{
int i = start;
foreach (var t in input)
yield return (i++, t);
}
}
class Program
{
static void Main(string[] args)
{
var s = new string[]
{
"Alpha",
"Bravo",
"Charlie",
"Delta"
};
foreach (var (i, o) in s.Enumerate())
Console.WriteLine($"{i}: {o}");
}
}
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));
}
As for a specific function that will do what you're asking, I don't know if .NET includes it. The quickest way, however, would just be to do something like this:
int id = 0;
foreach(var elem in someList)
{
... doStuff ...
id++;
}
EDIT: Here is a function that will do as you ask, using yield return
, but it has the downside of requiring one GC allocation per iteration:
public static IEnumerable<Tuple<int, T>> Enumerate<T>(IEnumerable<T> list)
{
int id = 0;
foreach(var elem in list)
{
yield return new Tuple<int, T>(id, elem);
id++;
}
}