Created
August 14, 2012 00:41
-
-
Save thomaslevesque/3345186 to your computer and use it in GitHub Desktop.
IEnumerable<T> memoization (based on http://www.kodefuguru.com/post/2012/08/13/Caching-LINQ-Results.aspx)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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