使用linq获取列表c#中部分匹配项的索引
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");
}
我有字符串列表。如果列表包含该部分字符串,则找出该项目的索引。请查看代码以获取更多信息。
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");
}