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
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
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;
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;
}