Circular Iterator : IEnumerator « Data Structure « C# / CSharp Tutorial






/*
Quote from
Accelerated C# 2005
# By Trey Nash
# ISBN: 1-59059-717-6
# 432 pp.
# Published: Aug 2006
*/

using System;
using System.Collections;
using System.Collections.Generic;

public class MainClass
{
    static void Main() {
        LinkedList<int> intList = new LinkedList<int>();
        for( int i = 1; i < 6; ++i ) {
            intList.AddLast( i );
        }

        CircularIterator<int> iter = new CircularIterator<int>(intList, intList.First);

        int counter = 0;
        foreach( int n in iter ) {
            Console.WriteLine( n );

            if( counter++ == 100 ) {
                iter.Stop();
            }
        }
    }
}

public class CircularIterator<T> : IEnumerable<T>
{
    public CircularIterator( LinkedList<T> list, LinkedListNode<T> start ) {
        enumerator = CreateEnumerator( list, start, false ).GetEnumerator();
        enumType = enumerator.GetType();
    }

    public void Stop() {
        enumType.GetField("stop").SetValue( enumerator, true );
    }

    private IEnumerator<T> enumerator;
    private Type enumType;

    private IEnumerable<T> CreateEnumerator( LinkedList<T> list, LinkedListNode<T> start, bool stop ) {
        LinkedListNode<T> current = null;
        do {
            if( current == null ) {
                current = start;
            } else {
                current = current.Next;
                if( current == null ) {
                    current = start;
                }
            }

            yield return current.Value;
        } while( !stop );
    }

    public IEnumerator<T> GetEnumerator() {
        return enumerator;
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1








11.44.IEnumerator
11.44.1.A simple example of an iterator.
11.44.2.Iterated values can be dynamically constructed.
11.44.3.Use named iterators
11.44.4.Use the Enumerable pattern
11.44.5.Implement IEnumerable and IEnumerator
11.44.6.Define custom enumerators and use foreach to loop through
11.44.7.Build your own IEnumerator/IEnumerable and use it in foreach loop
11.44.8.Circular Iterator
11.44.9.Iteration Sample
11.44.10.Iterator Workflow
11.44.11.IEnumerator and ArrayList, BitArray, Hashtable and array