![](/img/trans.png)
[英]Validate a Column in DataGridView using File.ReadAllLines?
[英]Is File.ReadAllLines lazy loaded when using with LINQ Where?
我想知道下面的代碼是否是惰性求值的,或者是否會以我處理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
, 可以在返回整個集合之前開始枚舉字符串集合 ; 當您使用ReadAllLines
, 必須等待返回整個字符串數組才能訪問該數組。 因此,當您使用非常大的文件時,ReadLines可以更高效。
但請注意,您必須小心使用ReadLines
因為您無法使用它兩次。 如果你第二次嘗試“執行”它,你將獲得一個ObjectDisposedException
因為底層流已經被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
更合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.