C# 如何在列表中查找字符串的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16534657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find an Index of a string in a list
提问by Simon Taylor
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.
是的,我知道它实际上并不是什么,而且它是错误的,因为它似乎正在寻找一个等于 npcID 的项目,而不是以它开头的行。
采纳答案by sa_ddam213
If you want "StartsWith" you can use FindIndex
如果你想要“StartsWith”,你可以使用 FindIndex
int index = txtLines.FindIndex(x => x.StartsWith("whatever"));
回答by dArc
if your txtLines is a List Type, you need to put it in a loop, after that retrieve the value
如果你的 txtLines 是一个列表类型,你需要把它放在一个循环中,然后检索值
int index = 1;
foreach(string line in txtLines) {
if(line.StartsWith(npcID)) { break; }
index ++;
}
回答by Olivia
Suppose txtLines was filled, now :
假设 txtLines 已填充,现在:
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> indexby this code : index.First();
现在你有一个包含所有 txtLines 元素索引的 int 列表。您可以List<int> index通过以下代码调用第一个元素:index.First();

