tsunami

log in
history

C#: EnumerableMemoizer

Luke Breuer
0001-01-01 05:00 UTC
tags: c#

using System.Collections.Generic;

namespace SaThreadToDb
{
    class EnumerableMemoizer<T> : IEnumerable<T>
    {
        private List<T> _cache = new List<T>();
        private IEnumerator<T> _e;

        public EnumerableMemoizer(IEnumerable<T> list)
        {
            _e = list.GetEnumerator();
        }

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 0; i < _cache.Count; i++)
                yield return _cache[i++];

            while (_e.MoveNext())
            {
                _cache.Add(_e.Current);
                yield return _e.Current;
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}