使用LINQ时,File.ReadAllLines是否延迟加载?

Cod*_*ist 4 c# linq lazy-loading file.readalllines

我想知道以下代码是否是惰性求值的,或者是否会以我处理可能的异常的方式崩溃ReadAllLines().我确定该Where条款是懒惰的评估,但我不确定我什么时候使用它ReadAllLines().可能的解释如何以及为什么会受到赞赏.

File.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...
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Tim*_*ter 9

File.ReadAllLines 不是延迟加载,它将所有内容加载到内存中.

string[]  allLines = File.ReadAllLines(filePath);
Run Code Online (Sandbox Code Playgroud)

如果您想使用LINQ的延迟执行,您可以使用File.ReadLines:

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

这也记录在案:

ReadLinesReadAllLines方法的区别如下:当你使用 ReadLines,你可以返回整个集合之前开始枚举字符串的集合 ; 在使用时ReadAllLines,必须等待返回整个字符串数组才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.

但请注意,您必须小心,ReadLines因为您不能使用它两次.如果您尝试"执行"它,您将第二次获得它,ObjectDisposedException因为已经处理了基础流.更新 此错误似乎已得到修复.

这将导致异常,例如:

var lines = File.ReadLines(path);
string header = lines.First();
string secondLine = lines.Skip(1).First();
Run Code Online (Sandbox Code Playgroud)

由于流仍处于打开状态,因此您无法使用它来写入同一文件.

File.WriteAllLines(path, File.ReadLines(path)); // exception:  being used by another process.
Run Code Online (Sandbox Code Playgroud)

在这些情况下File.ReadAllLines更合适.