与 LINQ Where 一起使用时,File.ReadAllLines 是否延迟加载?

问题描述 投票:0回答:1

我想知道下面的代码是否被延迟评估或者会以我处理

ReadAllLines()
可能异常的方式崩溃。我确定
Where
子句是惰性评估的,但我不确定何时将它与
ReadAllLines()
一起使用。 关于如何以及为什么的可能解释将不胜感激。

File.ReadAllLines Exceptions

var fileLines = File.ReadAllLines(filePath).Where(line =>
{
    line = line.Trim();
    return line.Contains("hello");
});

string search;
try
{
    search = fileLines.Single();
}
catch (Exception exception)
{
    ...log the exception...
}

提前致谢。

c# linq lazy-loading file.readalllines
1个回答
10
投票

File.ReadAllLines
不是延迟加载,而是全部加载到内存中。

string[]  allLines = File.ReadAllLines(filePath);

如果你想使用 LINQ 的延迟执行,你可以使用

File.ReadLines
代替:

var fileLines = File.ReadLines(filePath)
    .Where(line =>
    {
        line = line.Trim();
        return line.Contains("hello");
    });

这也是记录的

ReadLines
ReadAllLines
方法的区别如下:当您使用
ReadLines
可以开始枚举之前的字符串集合 整个系列都被归还;当你使用
ReadAllLines
时,你必须 等待整个字符串数组返回,然后才能访问 阵列。因此,当您处理非常大的文件时, ReadLines 可以更有效率。

但是请注意,您必须小心使用

ReadLines
,因为您不能使用它两次。如果你第二次尝试“执行”它,你会得到一个
ObjectDisposedException
,因为底层流已经被处理掉了。 更新这个错误似乎被修复了

这将导致异常例如:

var lines = File.ReadLines(path);
string header = lines.First();
string secondLine = lines.Skip(1).First();

你不能用它来写入同一个文件,因为流仍然是打开的。

File.WriteAllLines(path, File.ReadLines(path)); // exception:  being used by another process.

在这些情况下

File.ReadAllLines
更合适。

© www.soinside.com 2019 - 2024. All rights reserved.