This is C# version:
public static IEnumerable<string> ReadLinesEnumerable(string path) {
using ( var reader = new StreamReader(path) ) {
var line = reader.ReadLine();
while ( line != null ) {
yield return line;
line = reader.ReadLine();
}
}
}
But directly translating needs a mutable variable.
To answer the question whether there is a library function for encapsulating this pattern - there isn't a function exactly for this, but there is a function that allows you to generate sequence from some state called
Seq.unfold
. You can use it to implement the functionality above like this:The
sr
value represents the stream reader and is passed as the state. As long as it gives you non-null values, you can returnSome
containing an element to generate and the state (which could change if you wanted). When it readsnull
, we dispose it and returnNone
to end the sequence. This isn't a direct equivalent, because it doesn't properly disposeStreamReader
when an exception is thrown.In this case, I would definitely use sequence expression (which is more elegant and more readable in most of the cases), but it's useful to know that it could be also written using a higher-order function.
If you're using .NET 4.0, you can just use File.ReadLines.
On .NET 2/3 you can do:
and on .NET 4: