[英]compare list of strings with another string
我有1个长字符串,看起来像: "item1, item7, item9"
等。然后,我有了一个列表,看起来像:
"item2",
"item3",
"item9"
我想检查一下列表字符串是否与长字符串中的任何内容匹配。 我可以使用一个foreach循环,但是我在想必须有一个简单的LINQ表达式,但我似乎不太正确。
您可以尝试这样的事情:
var isContained = list.Any(x=>stringValue.Contains(x));
其中list
是字符串列表, stringValue
是您拥有的字符串。
在上面的代码中,我们使用Any
方法,该方法查找列表中是否有任何元素使我们提供的谓词为true
。 谓词有一个列表项作为输入,并检查该项目是否包含在stringValue
。 如果是这样,则返回true。 否则为假。
string longString = "item1,item7,item9";
List<string> myList=new List<string>(new string[]{"item2","item3","item9"});
if (myList.Any(str => longString.Contains(str)))
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("fail!");
}
怎么样:
// Set up the example data
String searchIn = "item1, item7, item9";
List<String> searchFor = new List<String>();
searchFor.Add("item2");
searchFor.Add("item3");
searchFor.Add("item9");
var firstMatch = searchFor.FirstOrDefault(p => { return -1 != searchIn.IndexOf(p); });
// firstMatch will contain null if no item from searchFor was found in searchIn,
// otherwise it will be a reference to the first item that was found.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.