【问题标题】:How to find an Index of a string in a list如何在列表中查找字符串的索引
【发布时间】:2013-05-08 05:32:39
【问题描述】:

所以我要做的是检索列表中以“whatever”开头的第一项的索引,我不知道该怎么做。

我的尝试(笑):

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

是的,我知道它实际上并不是任何东西,而且它是错误的,因为它似乎正在寻找一个等于 npcID 的项目,而不是以它开头的行。

【问题讨论】:

  • 它确实显示了字符串的索引。查看dotnetperls.com/indexof
  • 到底有什么问题?如果txtLines 是一个文本框,只需执行txtLines.Text.IndexOf(ncpID)
  • 抱歉刚刚修好了,由于某种原因代码没有粘贴。哦,修好了

标签: c# string list indexing


【解决方案1】:

如果你想要“StartsWith”,你可以使用FindIndex

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

【讨论】:

    【解决方案2】:

    如果你的 txtLines 是 List 类型,你需要把它放在一个循环中,然后检索值

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

    【讨论】:

    • 您可能希望在找到字符串时退出循环。
    【解决方案3】:

    假设 txtLines 已填满,现在:

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

    现在你有一个包含所有 txtLines 元素的 int 列表。您可以通过以下代码调用List&lt;int&gt; index 的第一个元素:index.First();

    【讨论】:

      猜你喜欢
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2021-12-24
      相关资源
      最近更新 更多