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

Cached

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

Source

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)
    {
        cache.Add(x);
        yield return x;
    }
}

Example

var cached = seq.Cached();

Author: beppemarazzi

Submitted on: 27 apr 2019

Language: C#

Type: IEnumerable<T>

Views: 4161