我有一个长字符串,看起来像:"item1, item7, item9"
等。
然后我有一个看起来像的列表:
"item2",
"item3",
"item9"
我想运行一个检查,看看是否有任何列表字符串与长字符串中的任何内容匹配。我可以使用foreach循环,但我认为必须有一个简单的LINQ表达式,我似乎无法做对。
答案 0 :(得分:4)
您可以尝试这样的事情:
var isContained = list.Any(x=>stringValue.Contains(x));
其中list
是字符串列表,stringValue
是您拥有的字符串。
在上面的代码中,我们使用Any
方法,该方法查看列表中是否有任何元素使我们提供的谓词为true
。谓词具有列表项作为输入,并检查此项是否包含在stringValue
中。如果是这样返回true。否则是假的。
答案 1 :(得分:0)
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!");
}
答案 2 :(得分:0)
怎么样:
// 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.