我遇到了一个逐行读取文件的实现,如下所示:
using (StreamReader reader = File.OpenText(path))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
但是我个人会这样做:
foreach (string line in File.ReadLines(path))
{
}
是否有任何理由选择一个而不是另一个?
最佳答案
客观地:
第一个是一条一条地挑选线,你做这个过程 在流式传输数据时。
第二个生成
IEnumerable<string>
一次然后你可以 开始处理这些行(来源 MSDN - 我很抱歉混合它 与ReadAllLines
一开始)。
有用吗?
- 从这个意义上说,第一个更“流畅”。因为你可以选择
随意采取/处理和中断/继续。每次你需要一行,你就拿一条,你处理它,然后你选择中断或继续。您甚至可以选择不再走任何线路(假设您在
yield
循环中有while
),直到您想随意返回 - 第二个会得到
IEnumerable<string>
(也就是说,在处理之前指定预期数据的信息)因此首先会产生一些开销。然而,需要注意的是,这个开销相对较小,因为IEnumerable
推迟实际执行,不像List
.一些good info至 read .
而来自 MSDN 以下是 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>.
关于c# - OpenText 与 ReadLines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916237/