我想知道下面的代码是否被延迟评估或者会以我处理
ReadAllLines()
可能异常的方式崩溃。我确定 Where
子句是惰性评估的,但我不确定何时将它与 ReadAllLines()
一起使用。
关于如何以及为什么的可能解释将不胜感激。
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...
}
提前致谢。
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
时,你必须 等待整个字符串数组返回,然后才能访问 阵列。因此,当您处理非常大的文件时, ReadLines 可以更有效率。ReadAllLines
但是请注意,您必须小心使用
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
更合适。