C#C
C#4y ago
Thinker

✅ Caching an IEnumerable

Simple question: I have an IEnumerable<T> which does some complex-ish calculations, and I would ideally like to cache the result of the enumerable, but while still allowing it to be lazy and not use something like ToArray() or ToList() which would enumerate the entire thing at once. So for instance, if the enumerable produces some elements using a Select, then if the user begins by enumerating the first three elements and nothing more, then those three elements would be cached and not be calculated again on successive enumerations. What would be the best way to do this?
Was this page helpful?