Cached IEnumerable

Checkout this out, it's a function that can convert any IEnumerable into a cached IEnumerable that can be enumerated many (or 0) times, but only calculates each element (at most) once, by caching the results in a List:

 public static IEnumerable<T> ToCachedEnumerable<T>(this IEnumerable<T> items) { IEnumerator<T> enumerator = items.GetEnumerator(); List<T> cache = new List<T>(); return ToCachedEnumerableHelper(enumerator, cache); } private static IEnumerable<T> ToCachedEnumerableHelper<T>(IEnumerator<T> enumerator, List<T> cache) { foreach (T t in cache) { yield return t; } while (enumerator.MoveNext()) { T t = enumerator.Current; cache.Add(t); yield return t; } } 

by DavidEichmann via /r/csharp

Leave a Reply