Is there something similar to python enumeration for linq

In python, I can easily get the index on iteration, for example.

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

How can I do something like this with linq?

+3
source share
2 answers

Of course. There is an overloadEnumerable.Select that takes Func<TSource, int, TResult>to project an element along with its index:

For instance:

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
+8
source

You can do this with an overload of Enumerable.Select , which contains the index variable. This provides access to the index, which you can use to create a new anonymous type. The following compiles and starts correctly:

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();
}
+4
source

Source: https://habr.com/ru/post/1731265/


All Articles