Language: C#
Perpetual Enumerator - never call Reset again
using System.Collections; using System.Collections.Generic; namespace nl4net { /// <summary> /// Wraps a standard IEnumerator<T> 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(); } } }
Tags:
Description:
Simple extension method to acquire a PerpetualEnumerator from any IEnumerable<T> can be found here: http://codepaste.net/33fofg
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

