OpenText与ReadLines [英] OpenText vs ReadLines
问题描述
我遇到了一种逐行读取文件的实现,如下所示:
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();
}
但是我个人会这样做:
foreach (string line in File.ReadLines(path))
{
}
有什么理由选择一个吗?
Is there any reason to pick one over the other?
推荐答案
客观地:
-
第一个是一个接一个地选择线路,然后执行此过程 当您流式传输数据时.
The first one is picking the line one by one and you do the process as you stream the data.
第二个立即生成IEnumerable<string>
,然后您可以
开始处理行(源 MSDN 一个>-我很抱歉将其混合
首先是ReadAllLines
.
The second one generates IEnumerable<string>
at once and then you can
start processing the lines (Source MSDN - my apologize to mix it
with ReadAllLines
at first).
有用吗?:
- 从这个意义上讲,第一个更流畅".因为你可以选择
随意采取/处理和中断/继续.每当您需要一条线时,就采取一条线,进行处理,然后选择中断或继续.您甚至可以选择不走任何其他行(假设您在
while
循环中有yield
),直到您想随意返回 - 第二个将获得
IEnumerable<string>
(即在处理之前指定所需数据的信息),因此首先会产生一些开销.但是要注意,与List
不同,由于IEnumerable
延迟了实际执行,因此此开销相对较小.一些良好的信息以
- 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
yield
in thewhile
loop) 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 asIEnumerable
defer the actual execution, unlikeList
. Some good info to read.
来自MSDN,以下是ReadLines
的用例:
And from MSDN The following are the use cases for ReadLines
:
对文件执行LINQ to Objects查询以获得一组过滤的 它的台词.
Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.
使用以下命令将返回的行集合写入文件中 File.WriteAllLines(String,IEnumerable< String>)方法,或将其附加
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>)方法.创建一个 立即填充的集合实例,该集合需要一个 IEnumerable< T>为其构造函数提供的字符串集合,例如 IList< T>或队列< T>.
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>.
这篇关于OpenText与ReadLines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!