[英]Get the index of a partially matching item in a list c# using linq
I have List of string. 我有字符串列表。 If the list contains that partial string then find out the index of that item.
如果列表包含该部分字符串,则找出该项目的索引。 Please have a look on code for more info.
请查看代码以获取更多信息。
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");
}
You can use List.FindIndex
: 您可以使用
List.FindIndex
:
int index = s.FindIndex(str => str.Contains("jkl")); // 1
if(index >= 0)
{
// at least one match, index is the first match
}
you can use this 你可以用这个
var index = s.Select((item,idx)=> new {idx, item }).Where(x=>x.item.Contains("jkl")).FirstOrDefault(x=>(int?)x.idx);
Edit 编辑
In case when using a List<string>
, FindIndex
is better to use. 如果使用
List<string>
,则最好使用FindIndex
。 But in my defence, using FindIndex
is not using LINQ as requested by OP ;-) 但是为了我的辩护,使用
FindIndex
并没有按照OP的要求使用LINQ ;-)
Edit 2 编辑2
Should have used FirstOrDefault
应该使用
FirstOrDefault
This is how I was using it without Linq and wanted to shorten it so posted this question. 这就是我在没有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.