Get index of Enumerator.Current in C#
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.
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
.
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).
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++;
}
}
链接地址: http://www.djcxy.com/p/52968.html