Force IEnumerable<T> to evaluate without calling .ToArray() or .ToList()
Is there a way to force an
IEnumerable<T>
collection to contain results without calling.ToArray()
or.ToList();
?
Yes, but it is perhaps not what you want:
IEnumerable<T> source = …;
IEnumerable<T> cached = new List<T>(source);
The thing is, IEnumerable<T>
is not a concrete type. It is an interface (contract) representing an item sequence. There can be any concrete type "hiding behind" this interface; some might only represent a query, others actually hold the queried items in memory.
If you want to force-evaluate your sequence so that the result is actually stored in physical memory, you need to make sure that the concrete type behind IEnumerable<T>
is a in-memory collection that holds the results of the evaluation. The above code example does just that.
You can use a foreach
loop:
foreach (var item in fooBars) { }
Note that this evaluates all items in fooBars
, but throws away the result immediately. Next time you run the same foreach
loop or .ToArray()
, .ToList()
, the enumerable will be evaluated once again.