'How to find an Index of a string in a list

So what I am trying do is retrieve the index of the first item, in the list, that begins with "whatever", I am not sure how to do this.

My attempt (lol):

List<string> txtLines = new List<string>();
//Fill a List<string> with the lines from the txt file.
foreach(string str in File.ReadAllLines(fileName)) {
  txtLines.Add(str);
}
//Insert the line you want to add last under the tag 'item1'.
int index = 1;
index = txtLines.IndexOf(npcID);

Yea I know it isn't really anything, and it is wrong because it seems to be looking for an item that is equal to npcID rather than the line that begins with it.



Solution 1:[1]

If you want "StartsWith" you can use FindIndex

 int index = txtLines.FindIndex(x => x.StartsWith("whatever"));

Solution 2:[2]

if your txtLines is a List Type, you need to put it in a loop, after that retrieve the value

int index = 1;
foreach(string line in txtLines) {
     if(line.StartsWith(npcID)) { break; }
     index ++;
}

Solution 3:[3]

Suppose txtLines was filled, now :

List<int> index = new List<int>();
for (int i = 0; i < txtLines.Count(); i++)
{
    index.Add(i);
}

now you have a list of int contain index of all txtLines elements. you can call first element of List<int> index by this code : index.First();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sa_ddam213
Solution 2
Solution 3 The_Black_Smurf