问题
I came across an implementation of reading a file line by line that looks like this:
using (StreamReader reader = File.OpenText(path))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
However personally I would do just this:
foreach (string line in File.ReadLines(path))
{
}
Is there any reason to pick one over the other?
回答1:
Objectively:
The first one is picking the line one by one and you do the process as you stream the data.
The second one generates
IEnumerable<string>at once and then you can start processing the lines (Source MSDN - my apologize to mix it withReadAllLinesat first).
Usefulness?:
- The first one is more "fluid" in that sense. Because you can choose
to take/process and break/continue at will. Everytime you need a line, you take one, you process it and then you choose to break or continue. You can even choose to not take any further line (suppose you have
yieldin thewhileloop) till you want to come back at will - The second one would get
IEnumerable<string>(that is, to specify the info of the expected data before process) thus giving slightly overhead at first. It is to be noted, however, that this overhead is relatively small asIEnumerabledefer the actual execution, unlikeList. Some good info to read.
And from MSDN The following are the use cases for ReadLines:
Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.
Write the returned collection of lines to a file with the File.WriteAllLines(String, IEnumerable<String>) method, or append them to an existing file with the
File.AppendAllLines(String, IEnumerable<String>) method. Create an immediately populated instance of a collection that takes an IEnumerable<T> collection of strings for its constructor, such as a IList<T> or a Queue<T>.
回答2:
Method 1
Is more verbose than method 2. So more chance of things being stuffed up.
Method 2
Is more concise and encapsulates the intent more directly - much easier to read and follow also less chance of stuffing things up (like forgetting to dispose of the reader etc).
来源:https://stackoverflow.com/questions/34916237/opentext-vs-readlines