The solution you have is functionally correct, but its performance is poor. Usually, when you work with a list style structure, you expect GetNext return the result in O (1) time, but this solution is O (N).
public sealed class WrappingIterator<T> { private IList<T> _list; private int _index; public WrappingIterator<T>(IList<T> list, int index) { _list = list; _index = index; } public T GetNext() { _index++; if (_index == _list.Count) { _index = 0; } return _list[_index]; } public static WrappingIterator<T> CreateAt(IList<T> list, T value) { var index = list.IndexOf(value); return new WrappingIterator(list, index); } }
The initial call to CreateAt is O (N) here, but subsequent calls to GetNext are O (1).
IList<string> list = ...; var iterator = WrappingIterator<string>.CreateAt(list, "B"); Console.WriteLine(iterator.GetNext());
Jaredpar
source share