[英]Check if a particular string is contained in a list of strings
I'm trying to search a string to see if it contains any strings from a list,我正在尝试搜索一个字符串以查看它是否包含列表中的任何字符串,
var s = driver.FindElement(By.Id("list"));
var innerHtml = s.GetAttribute("innerHTML");
foreach(var str in list)
{
if (innerHtml.Contains(str))
{
// match found, do your stuff.
}
}
You can do it with LINQ by applying Contains
to innerHtml
for each of the items on the list: 您可以使用LINQ对innerHtml
中的每个项目应用Contains
到innerHtml
来执行此操作:
var matches = list.Where(item => innerHtml.Contains(item)).ToList();
Variable matches
would contain a subset of strings from the list
which are matched inside innerHtml
. 变量matches
将包含list
的字符串子集,这些字符串在innerHtml
中匹配。
Note: This approach does not match at word boundaries, which means that you would find a match of "One"
when innerHtml
contains "Onerous"
. 注意:此方法与单词边界不匹配,这意味着当innerHtml
包含"Onerous"
时,您会找到匹配的"One"
"Onerous"
。
You can do this in the following way: 您可以通过以下方式执行此操作:
int result = list.IndexOf(innerHTML);
It will return the index of the item with which there is a match, else if not found it would return -1. 它将返回匹配项的索引,否则如果找不到则返回-1。
If you want a string output, as mentioned in the question, you may do something like: 如果你想要一个字符串输出,如问题所述,你可以做类似的事情:
if (result != -1)
Console.WriteLine(list[result] + " matched.");
else
Console.WriteLine("No match found");
Another simple way to do this is: 另一种简单的方法是:
string matchedElement = list.Find(x => x.Equals(innerHTML));
This would return the matched element if there is a match, otherwise it would return a null. 如果匹配则返回匹配的元素,否则返回null。
For those who want to serach Arrray of chars in another list of strings对于那些想要在另一个字符串列表中搜索字符数组的人
List WildCard = new() { " ", "%", "?"<\/em>列表通配符 = new() { " ", "%", "?"<\/em> };<\/em> };<\/em> List PlateNo = new() { "13eer", "rt4<\/em> 444", "45566" }; List PlateNo = new() { "13eer", "rt4<\/em> 444", "45566" };
if (WildCard.Any(x => PlateNo.Any(y => y.Contains(x)))) Console.WriteLine("Plate has wildchar}"); if (WildCard.Any(x => PlateNo.Any(y => y.Contains(x)))) Console.WriteLine("Plate has wildchar}");
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.