2

Possible Duplicate:
(C#) Get index of current foreach iteration

Good morning,

Is there any way I can get the index of an Enumerator's current element (in the case, a character in a string) without using an ancillary variable? I know this would perhaps be easier if I used a while or for cicle, but looping through a string using an enumerator is more elegant... The only drawback for the case is that I really need to get each character's current index.

Thank you very much.

Community
  • 1
  • 1
Miguel
  • 3,346
  • 8
  • 36
  • 66

3 Answers3

5

No, the IEnumerator interface does not support such functionality.

If you require this, you will either have to implement this yourself, or use a different interface like IList.

Pieter van Ginkel
  • 28,744
  • 8
  • 70
  • 108
1

No there isn't. If you really need the index the most elegant way is to use for a loop. Using the iterator pattern is actually less elegant (and slower).

bitbonk
  • 47,402
  • 35
  • 179
  • 273
0

Linq's Select has fitting overloads. But you could use something like this:

foreach(var x in "ABC".WithIndex())
{
    Console.Out.WriteLine(x.Value + " " + x.Index);
}

using these helpers:

public struct ValueIndexPair<T>
{
    private readonly T mValue;
    private readonly int mIndex;

    public T Value { get { return mValue; } }
    public int Index { get { return mIndex; } }

    public override string ToString()
    {
        return "(" + Value + "," + Index + ")";
    }

    public ValueIndexPair(T value, int index)
    {
        mValue = value;
        mIndex = index;
    }
}

public static IEnumerable<ValueIndexPair<T>> WithIndex<T>(this IEnumerable<T> sequence)
{
    int i = 0;
    foreach(T value in sequence)
    {
        yield return new ValueIndexPair<T>(value, i);
        i++;
    }
}
gevorg
  • 4,535
  • 4
  • 34
  • 51
CodesInChaos
  • 103,479
  • 23
  • 206
  • 257