Skip to content

Instantly share code, notes, and snippets.

@uchida
Created November 28, 2011 13:55
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save uchida/1400476 to your computer and use it in GitHub Desktop.
Save uchida/1400476 to your computer and use it in GitHub Desktop.
C# sample code for equivalent of python enumerate()
// GWLlosa's answer in http://stackoverflow.com/questions/521687/c-sharp-foreach-with-index
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumerateTest {
class Program {
static void Main(string[] args) {
List<int> list = new List<int> {4, 2, 3, 1, 8};
foreach (var iter in list.Select((Value, Index) => new {Value, Index})) {
Console.WriteLine("{0}: {1}", iter.Index, iter.Value);
}
Console.ReadLine();
}
}
}
@magicleon94
Copy link

Nice!

@Zodt
Copy link

Zodt commented Aug 31, 2018

@euandmj
Copy link

euandmj commented Sep 22, 2020

Throwing in my 2p. personlly feel this small utility wrapper offers the closest thing to the Python enumerate:

public static IEnumerable<(int index, T value)> Enumerate<T>(IEnumerable<T> coll)
            => coll.Select((i, val) => (val, i));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment