2015-11-25 50 views
1

我有字符串列表。如果列表包含該部分字符串,則找出該項目的索引。請查看代碼以獲取更多信息。使用linq獲取列表中部分匹配項目的索引

List<string> s = new List<string>(); 
s.Add("abcdefg"); 
s.Add("hijklm"); 
s.Add("nopqrs"); 
s.Add("tuvwxyz"); 

if(s.Any(l => l.Contains("jkl")))//check the partial string in the list 
{ 
    Console.Write("matched"); 

    //here I want the index of the matched item. 
    //if we found the item I want to get the index of that item. 

} 
else 
{ 
    Console.Write("unmatched"); 
} 

回答

5

您可以使用List.FindIndex

int index = s.FindIndex(str => str.Contains("jkl")); // 1 
if(index >= 0) 
{ 
    // at least one match, index is the first match 
} 
+0

如果項目不在列表中,則導致異常。任何選擇? –

+0

@SandeepKushwah:如果項目不在那裏,索引是-1,所以你只需要檢查。 –

+0

感謝:) –

0

您可以使用List<string>時使用此

var index = s.Select((item,idx)=> new {idx, item }).Where(x=>x.item.Contains("jkl")).FirstOrDefault(x=>(int?)x.idx); 

編輯

在情況下,FindIndex是更好地使用。 但在我的防守,利用FindIndex沒有使用LINQ的要求由OP ;-)

編輯2

應該使用FirstOrDefault

+0

我正在尋找最簡單的解決方案,因此接受蒂姆斯的答案。感謝您的努力! –

0

這是我如何使用它沒有LINQ和希望縮短它,所以發佈這個問題。

List<string> s = new List<string>(); 
s.Add("abcdefg"); 
s.Add("hijklm"); 
s.Add("nopqrs"); 
s.Add("tuvwxyz"); 
if(s.Any(l => l.Contains("tuv"))) 
{ 
    Console.Write("macthed"); 
    int index= -1; 
    //here starts my code to find the index 
    foreach(string item in s) 
    { 
    if(item.IndexOf("tuv")>=0) 
    { 
     index = s.IndexOf(item); 
     break; 
    } 

    } 
    //here ends block of my code to find the index 
    Console.Write(s[index]); 
    } 
    else 
    Console.Write("unmacthed"); 
} 
相關問題