Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created August 14, 2012 00:41
Show Gist options
  • Save thomaslevesque/3345186 to your computer and use it in GitHub Desktop.
Save thomaslevesque/3345186 to your computer and use it in GitHub Desktop.
public static class Sequence
{
public static IEnumerable<T> Memoize<T>(this IEnumerable<T> sequence)
{
return new MemoizedSequence<T>(sequence);
}
}
// This code is for illustration and is not production-ready.
internal class MemoizedSequence<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _source;
private readonly List<T> _cache;
private int _lastCachedIndex;
private IEnumerator<T> _inner;
private bool _disposed;
public MemoizedSequence(IEnumerable<T> source)
{
_source = source;
_cache = new List<T>();
_lastCachedIndex = -1;
}
#region Implementation of IEnumerable
public IEnumerator<T> GetEnumerator()
{
if (_inner == null)
_inner = _source.GetEnumerator();
for (int i = 0; i <= _lastCachedIndex; i++)
{
yield return _cache[i];
}
while (!_disposed && _inner.MoveNext())
{
_cache.Add(_inner.Current);
_lastCachedIndex++;
yield return _inner.Current;
}
_inner.Dispose();
_disposed = true;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment