CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Perpetual Enumerator - never call Reset again

182 Views
Copy Code Show/Hide Line Numbers
using System.Collections;
using System.Collections.Generic;
 
namespace nl4net
{
    /// <summary>
    /// Wraps a standard IEnumerator&lt;T&gt; to provide
    /// iteration over a generic collection that automatically 
    /// resets to the beginning once it reaches the end.
    /// </summary>
    /// <typeparam name="T">The type of objects to enumerate.</typeparam>
    public class PerpetualEnumerator<T>
        : IEnumerator<T>
    {
        readonly IEnumerator<T> _enumerator;
 
        public PerpetualEnumerator(IEnumerable<T> items)
        {
            Guard.Argument("items").IsNotNull(items);
 
            _enumerator = items.GetEnumerator();
            _enumerator.MoveNext();
        }
 
        /// <summary>
        /// Gets the element in the collection at the current position of the enumerator.
        /// </summary>
        public T Current
        {
            get { return _enumerator.Current; }
        }
 
        /// <summary>
        /// Defines a method to release allocated resources.
        /// </summary>
        public void Dispose()
        {
            _enumerator.Dispose();
        }
 
        /// <summary>
        /// Gets the current element in the collection.
        /// </summary>
        object IEnumerator.Current
        {
            get { return this.Current; }
        }
 
        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// Always returns true since the enumerator is reset once it 
        /// reaches the end of the collection.
        /// </returns>
        public bool MoveNext()
        {
            if (!_enumerator.MoveNext())
            {
                this.Reset();
            }
            return true;
        }
 
        /// <summary>
        /// Sets the enumerator to its initial position, which is before the first element in the collection.
        /// </summary>
        public void Reset()
        {
            _enumerator.Reset();
            _enumerator.MoveNext();
        }
    }
}
by Al Gonzalez
  June 17, 2010 @ 9:08pm
Tags:
Description:
Simple extension method to acquire a PerpetualEnumerator from any IEnumerable<T> can be found here: http://codepaste.net/33fofg

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate