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

标签 c# linq lazy-loading file.readalllines

我想知道以下代码是否被惰性求值,或者是否会在我处理 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...
}

提前致谢

最佳答案

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 and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, 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/

相关文章:

c# - 使 ClickOnce 更新成为强制性的?

c# - System.Web.HttpRequestValidationException : A potentially dangerous Request. 从机器人客户端检测到表单值?

java - Hibernate 分离延迟加载关系

c# - 如何在 C# 中延迟加载 DataGridView

c# - 使用 Linq 按索引求和

c# - 有没有办法检测用户是从团队移动应用程序还是桌面应用程序输入?

c# - 合并列表并从两者中选择属性

c# - Linq .SingleOrDefault - 如何为自定义类设置默认值?

c# - 提取 IEnumerable<T> 中其键值等于 IEnumerable<U> 中的键值之一的项目

c# - 流利的 NHibernate + 禁用 LazyLoad