Simon Taylor
Simon Taylor

Reputation: 523

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.

Upvotes: 22

Views: 84745

Answers (3)

Olivia
Olivia

Reputation: 27

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();

Upvotes: -1

dArc
dArc

Reputation: 342

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

Upvotes: 2

sa_ddam213
sa_ddam213

Reputation: 43596

If you want "StartsWith" you can use FindIndex

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

Upvotes: 57

Related Questions