Search code examples
c#indexingtext-filesfile.readalllinesline-count

Get Second Instance of Reading a Text File using StartsWith()


I'm reading from a text file to find the Line Index where a certain line starts with my Criteria.
Turns out there are actually two instances of my desired criteria and I want to get the second one.
How would I amend the below code to Skip the first instance and get the second?

var linesB = File.ReadAllLines(In_EmailBody);
int LineNumberB = 0;
string criteriaB = "T:";
for (LineNumberB = 0; LineNumberB < linesB.Length; LineNumberB++){
    if(linesB[LineNumberB].StartsWith(criteriaB))
        break;
}

I use the result after and compare it to another criteria to find out the number of lines between the two results.


Solution

  • You could use following LINQ query to simplify your task:

    List<string> twoMatchingLines = File.ReadLines(In_EmailBody)
        .Where(line = > line.StartsWith(criteriaB))
        .Take(2)
        .ToList();
    

    Now you have both in the list.

    string first = twoMatchingLines.ElementAtOrDefault(0);  // null if empty
    string second = twoMatchingLines.ElementAtOrDefault(1); // null if empty or only one
    

    If you want to use the for-loop(your last sentence suggests it), you could count the matching lines:

    int matchCount = 0;
    for (int i = 0; i < linesB.Length; i++)
    {
        if(linesB[i].StartsWith(criteriaB) && ++matchCount == 2)
        {
            // here you are
        }
    }