Skip to content

Instantly share code, notes, and snippets.

@orlys
Created August 19, 2020 07:35
Show Gist options
  • Save orlys/a26adb071953c150029e3c2a96cf0859 to your computer and use it in GitHub Desktop.
Save orlys/a26adb071953c150029e3c2a96cf0859 to your computer and use it in GitHub Desktop.
public interface IIndexedEnumerator<T> : IEnumerator<T>
{
int Index
{
get;
}
bool IsOdd
{
get;
}
}
public static class IndexedEnumerationExtensions
{
public static IIndexedEnumerator<T> GetIndexedEnumerator<T>(this IEnumerable<T> collection)
{
return new IndexedEnumerator<T>(collection.ToArray());
}
public class IndexedEnumerator<T> : IIndexedEnumerator<T>
{
private T[] _array;
internal IndexedEnumerator(T[] array)
{
_array = array;
this.Reset();
}
public bool IsOdd => (this.Index & 1) == 1;
public int Index
{
get;
private set;
}
public T Current => this._array[this.Index];
public void Dispose()
{
_array = null;
}
public bool MoveNext()
{
this.Index++;
return this.Index < this._array.Length;
}
public void Reset()
{
this.Index = -1;
}
object IEnumerator.Current => this.Current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment