使用linq获取列表c#中部分匹配项的索引

San*_*wah 1 c# linq list indexof

我有字符串列表.如果列表包含该部分字符串,则找出该项的索引.请查看代码以获取更多信息.

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");
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

你可以使用List.FindIndex:

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