[英]Get the index of a partially matching item in a list c# using 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");
}
您可以使用List.FindIndex
:
int index = s.FindIndex(str => str.Contains("jkl")); // 1
if(index >= 0)
{
// at least one match, index is the first match
}
你可以用這個
var index = s.Select((item,idx)=> new {idx, item }).Where(x=>x.item.Contains("jkl")).FirstOrDefault(x=>(int?)x.idx);
編輯
如果使用List<string>
,則最好使用FindIndex
。 但是為了我的辯護,使用FindIndex
並沒有按照OP的要求使用LINQ ;-)
編輯2
應該使用FirstOrDefault
這就是我在沒有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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.