2013-05-14 49 views
15

所以我试图做的是检索第一个项目,在列表中,以“无论”开头的索引,我不知道如何做到这一点。如何在列表中找到一个字符串的索引

我尝试(笑):

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,而不是行中的项目从它开始。

+0

它确实会显示字符串的索引。请查看http://www.dotnetperls.com/indexof – Sunny 2013-05-14 03:34:19

+0

究竟是什么问题?如果'txtLines'是一个文本框,只需执行'txtLines.Text.IndexOf(ncpID)'。 – Matthew 2013-05-14 03:35:57

+0

对不起,只是修复它,出于某种原因代码没有粘贴。哦,很好的修复 – 2013-05-14 03:37:54

回答

40

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

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

谢谢,像一个魅力 – 2013-05-14 03:52:17

2

如果您txtLines是一个列表类型,你需要把它放在一个循环,之后检索值

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

你可能想要退出循环的某个时候,当你找到字符串。 – siride 2013-05-14 03:43:04

+0

thx你的输入,我已经改变了代码 – dArc 2013-05-14 03:47:01

+0

这帮助我很多。谢谢。 :) – 2013-09-23 10:04:18

-1

假设txtLines被填充了,现在:

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

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

相关问题