I am looking for a data structure that I can fill with items, and like an IEnumerator call MoveNext() but when it gets to the end of the list automatically loop back to the beginning. I can think of two ways to do this, either use a linked list and link it to itself, or just write the logic to check if IEnumerator.Current is null and reset, both rather trivial to write but I wanted to first check if there was something in the framework that already can do this.
It would look something like this:
public interface IInfiniteEnumerable<T>
{
bool MoveNext();
T Current();
}
Edit: As per the answer this does the trick:
class Program
{
static void Main(string[] args)
{
var lst = new List<string>
{
"A",
"B",
"C"
};
IEnumerator<string> enumerator = lst.RepeatIndefinitely().GetEnumerator();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
enumerator.MoveNext();
Console.WriteLine(enumerator.Current);
Console.ReadLine();
}
}
public static class Extensions
{
public static IEnumerable<T> RepeatIndefinitely<T>(this IEnumerable<T> source)
{
while (true)
{
foreach (var item in source)
{
yield return item;
}
}
}
}