Home > Back-end >  TakeWhile() with conditions in multiple lines
TakeWhile() with conditions in multiple lines

Time:04-29

I have a text file with a few thousand lines of texts. A Readlines() function reads each line of the file and yield return the lines.

I need to skip the lines until a condition is met, so it's pretty easy like this:

var lines = ReadLines().SkipWhile(x => !x.Text.Contains("ABC Header"))

The problem I am trying to solve is there is another condition -- once I find the line with "ABC Header", the following line must contain "XYZ Detail". Basically, the file contains multiple lines that have the text "ABC Header" in it, but not all of these lines are followed by "XYZ Detail". I only need those where both of these lines are present together.

How do I do this? I tried to add .Where after the SkipWhile, but that doesn't guarantee the "XYZ Detail" line is immediately following the "ABC Header" line. Thanks!

CodePudding user response:

// 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}");
}

resulted in output:

Found results:
ABC Header 2 / XYZ Detail 2
ABC Header 3 / XYZ Detail 3

For input File

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() in my test is implemented nearly identical to yours.

  • Related