3 ms·
I guess you'd fix that by doing this? lines = ReadLines(file).ToList(); ToList() is the go-to method to force eager evaluation of a lazy enumeration.
by SideburnsOfDoom 14y ago
I guess you'd fix that by doing this?
lines = ReadLines(file).ToList();
ToList() is the go-to method to force eager evaluation of a lazy enumeration.
- gjulianm 14y agoOf course, but you can only do that if you know that ReadLines is using yield-return. If this method were to be used by other people you should use a temporary list to read all the stream before returning from the method; it's the expected behaviour.
- SideburnsOfDoom 14y agoNot just yield return. In quite a few different circumstances LINQ will return an IEnumerable<T> that is a wrapper over a query that won't be executed until you try and pull results out of it. LINQ Queries can wrap database queries, http results, active directory, file system or anything else. And as you note, enumerating it twice can mean doing the underlying query twice, with potentially differing results.