Is there something similar to python's enumerate for 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?
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
You can do this with the overload of Enumerable.Select which provides an index variable. This provides access to the index, which you can use to generate a new anonymous type. The following compiles and runs properly:
static void Main()
{
var letters = new char[] { 'a', 'b', 'c' };
var results = letters.Select((l, i) => new { Letter = l, Index = i });
foreach (var result in results)
{
Console.WriteLine("{0} / {1}", result.Letter, result.Index);
}
Console.ReadKey();
}
精彩评论