2

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
craig157
  • 355
  • 1
  • 3
  • 18
  • 1
    Why don't you count the occurences which match the criteria? As soon the count exceeds a certain value (in your case 2), break? – Odrai Apr 02 '21 at 13:42
  • 1
    You should be using IndexOf (not StartsWith). The second occurrence can be found by using Substring(indexof + 1).IndexOf which is the start position of 2nd occurrence. The 2nd occurrence you have to add the first index with the second index. – jdweng Apr 02 '21 at 13:50

1 Answers1

4

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
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939