2013-05-14 92 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();

相關問題