Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of PHP's InfiniteIterator in .NET?

I had a discussion on PHP's InfiniteIterator with a friend.

Is there an equivalent of it in the .NET world?

like image 214
Pascal Paradis Avatar asked Apr 19 '12 00:04

Pascal Paradis


2 Answers

Not built-in but easy to write:

public static IEnumerable<T> RepeatInfinitely<T>(this IEnumerable<T> sequence)
{
 while(true) {
  foreach(var item in sequence)
   yield return item;
 }
}
like image 83
usr Avatar answered Oct 12 '22 08:10

usr


you can just roll your own.

public class InfiniteEnumerator: System.Collections.IEnumerator
{
    private System.Collections.IEnumerator  _m_enumerator;
    public InfiniteEnumerator(System.Collections.IEnumerator enumerator)
    {
        _m_enumerator = enumerator;
    }

    public object Current
    {
        get { return _m_enumerator.Current; }
    }

    public bool MoveNext()
    {
        if (!_m_enumerator.MoveNext())
        {
            _m_enumerator.Reset();
            return _m_enumerator.MoveNext();
        }
        else
        {
            return true;
        }
    }

    public void Reset()
    {
        _m_enumerator.Reset();
    }
}
like image 27
Chui Tey Avatar answered Oct 12 '22 09:10

Chui Tey