Search code examples
c#indexof

Get IndexOf if next line equals text


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


Solution

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