0

I need to get the index of a specific line in a List<string> if the next line equals the variable

List:
Chapter
1
He 
Was
Chapter
2
She
Is

I want the IndexOf "Chapter" where the next line equals 2

Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
Dman
  • 534
  • 12
  • 31

2 Answers2

4

The thing is, using IndexOf, you get the first occurrence. Instead, you could check for all occurrences of "Chapter", check if the value of the following index is 2.

for(int i = 0; i < list.Count - 1; i++){
    if ("Chapter".Equals(list[i]) && "2".Equals(list[i+1]))
        answerIndex = i;
Chrimle
  • 458
  • 1
  • 4
  • 10
2

try this

var index=GetIndex(list,"Chapter","2");

public int GetIndex( List<string> list, string current, string next)
{
    var previous = string.Empty;
    var index = 0;
    foreach (var item in list)
    {
        if (item == next && previous == current) return index-1;
        index++;
        previous = item;
    }
    return -1;
}
Serge
  • 28,094
  • 4
  • 11
  • 35