Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something similar to python's enumerate for linq

Tags:

python

.net

linq

In python I can easily get an index when iterating e.g.

>>> letters = ['a', 'b', 'c']
>>> [(char, i) for i, char in enumerate(letters)]
[('a', 0), ('b', 1), ('c', 2)]

How can I do something similar with linq?

like image 565
ScottS Avatar asked Feb 03 '10 19:02

ScottS


1 Answers

Sure. There is an overload of Enumerable.Select that takes a Func<TSource, int, TResult> to project an element together with its index:

For example:

char[] letters = new[] { 'a', 'b', 'c' };
var enumerate = letters.Select((c, i) => new { Char = c, Index = i });
foreach (var result in enumerate) {
    Console.WriteLine(
        String.Format("Char = {0}, Index = {1}", result.Char, result.Index)
    );
}

Output:

Char = a, Index = 0
Char = b, Index = 1
Char = c, Index = 2
like image 112
jason Avatar answered Nov 14 '22 21:11

jason