我有一個包含幾千行文本的文本檔案。Readlines() 函式讀取檔案的每一行并 yield 回傳這些行。
我需要跳過這些行,直到滿足條件,所以這很簡單:
var lines = ReadLines().SkipWhile(x => !x.Text.Contains("ABC Header"))
我要解決的問題是存在另一種情況——一旦我找到帶有“ABC Header”的行,下面的行必須包含“XYZ Detail”。基本上,該檔案包含多行,其中包含文本“ABC Header”,但并非所有這些行都后跟“XYZ 詳細資訊”。我只需要這兩條線同時存在的那些。
我該怎么做呢?我嘗試在 SkipWhile 之后添加 .Where,但這并不能保證“XYZ 詳細資訊”行緊跟在“ABC 標題”行之后。謝謝!
uj5u.com熱心網友回復:
// See https://aka.ms/new-console-template for more information
using Experiment72045808;
string? candidate = null;
List<(string, string)> results = new();
foreach (var entry in FileReader.ReadLines())
{
if (entry is null) continue;
if (candidate is null)
{
if (entry.Contains("ABC Header"))
{
candidate = entry;
}
}
else
{
// This will handle two adjacend ABC Header - Lines.
if (entry.Contains("ABC Header"))
{
candidate = entry;
continue;
}
// Add to result set and reset.
if (entry.Contains("XYZ Detail"))
{
results.Add((candidate, entry));
candidate = null;
}
}
}
Console.WriteLine("Found results:");
foreach (var result in results)
{
Console.WriteLine($"{result.Item1} / {result.Item2}");
}
導致輸出:
Found results:
ABC Header 2 / XYZ Detail 2
ABC Header 3 / XYZ Detail 3
對于輸入檔案
Line 1
Line 2
ABC Header 1
Line 4
Line 5
ABC Header 2
XYZ Detail 2
Line 6
Line7
ABC Header 3
XYZ Detail 3
Line 8
Line 9
FileReader.ReadResults()在我的測驗中實作的幾乎與您的相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467143.html
上一篇:基本回圈登錄選單
下一篇:無法從xml節點獲取值
