您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在C#中逐行读取文件

在C#中逐行读取文件

您可以使用迭代器块轻松编写基于LINQ的行读取器:

static IEnumerable<SomeType> ReadFrom(string file) {
    string line;
    using(var reader = File.OpenText(file)) {
        while((line = reader.ReadLine()) != null) {
            SomeType newRecord = /* parse line */
            yield return newRecord;
        }
    }
}

或让乔恩开心:

static IEnumerable<string> ReadFrom(string file) {
    string line;
    using(var reader = File.OpenText(file)) {
        while((line = reader.ReadLine()) != null) {
            yield return line;
        }
    }
}
...
var typedSequence = from line in ReadFrom(path)
                    let record = ParseLine(line)
                    where record.Active // for example
                    select record.Key;

那么您将ReadFrom(...)获得一个无缓冲的懒惰评估序列,非常适合Where等。

请注意,如果使用OrderBy或standard GroupBy,它将必须在内存中缓冲数据;如果需要分组和聚合,则“ PushLINQ”具有一些精美的代码,可让您对数据执行聚合但将其丢弃(不进行缓冲)。乔恩的解释在这里

c# 2022/1/1 18:17:08 有411人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶