Skip to content

Instantly share code, notes, and snippets.

@tombatron
Last active April 18, 2017 10:42
Show Gist options
  • Save tombatron/5b074b67587c10e66112299113345b7d to your computer and use it in GitHub Desktop.
Save tombatron/5b074b67587c10e66112299113345b7d to your computer and use it in GitHub Desktop.
Python's `enumerate` in C# 7.
void Main()
{
var items = new []{ "first", "second", "third" };
foreach(var (item, index) in Enumerate(items))
{
Console.WriteLine($"{item} is index {index}.");
}
}
public static IEnumerable<(T, int)> Enumerate<T>(IEnumerable<T> enumerable)
{
var currentIndex = 0;
foreach(var e in enumerable)
{
yield return (e, currentIndex);
currentIndex++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment