[英]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.