Created
November 28, 2011 13:55
-
-
Save uchida/1400476 to your computer and use it in GitHub Desktop.
C# sample code for equivalent of python enumerate()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} | |
} |
I'd rather do like that
https://gist.github.com/Zodt/09c484c224f8a8bd11d96fe3ab962904
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
Nice!