ExtensionMethod.NET Home of 829 C#, Visual Basic, F# and Javascript extension methods


Cache result of IEnumerable iteration. Similar to other implemetations with two advantages: 1 - Not flawed (Dispose of IEnumerator done by compiler) 2- Simplier


public static IEnumerable<T> Cached<T>(this IEnumerable<T> e)
    if (e is ICollection<T> c)
        return CachedIterator(e, new List<T>(c.Count));
    return CachedIterator(e, new LinkedList<T>());

private static IEnumerable<T> CachedIterator<T>(IEnumerable<T> e, ICollection<T> cache)
    foreach (var x in cache)
        yield return x;

    foreach (var x in e)
        yield return x;


var cached = seq.Cached();

Author: beppemarazzi

Submitted on: 27 apr 2019

Language: C#

Type: IEnumerable<T>

Views: 1614