OpenText与ReadLines [英] OpenText vs ReadLines

查看:112
本文介绍了OpenText与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).

有用吗?:

  • 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 the while 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 as IEnumerable defer the actual execution, unlike List. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆