我想知道以下代码是否被惰性求值,或者是否会在我处理 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");
});
这也是documented :
The
ReadLines
andReadAllLines
methods differ as follows: When you useReadLines
, you can start enumerating the collection of strings before the whole collection is returned; when you useReadAllLines
, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.
但是请注意,您必须小心使用 ReadLines
,因为您不能使用它两次。如果您尝试第二次“执行”它,您将得到一个 ObjectDisposedException
,因为底层流已经被释放。 更新 This bug seems to be fixed.
这会导致异常例如:
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
更合适。
关于c# - 与 LINQ Where 一起使用时,File.ReadAllLines 是否延迟加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726888/