将两个字符串拆分为List <string>并使用Linq进行比较

时间:2018-11-01 20:14:50

标签: c# linq

我有一个带有字符串属性“ Color”的对象列表。我需要使用空格分隔符将字符串拆分为一个列表,并将该列表与另一个列表进行比较,以查看是否使用Linq匹配其中包含的任何字符串。

 string searchString = "I like sand";
 List<string> searches = searchString.Split(' ').ToList();

 //Determine if matches exists anywhere between the 2 strings using linq
 List<myObject> obj = myObjectList.Where(x=> searches.Any(a=>x.Color.Contains(a))).Any();

使用当前的Linq查询,我只能找到完全匹配的内容。因此,假设我的Objects Color属性等于“ sand”,查询将返回一个匹配项,但是如果我的Color等于“沙丘”之类的两个单词,则我的查询将不返回匹配项。

此示例应提供帮助,帮助您说明匹配结果需要返回什么。

//Two strings should return a match as the word sand is in both
"I like sand"
"sand dune"

//Two strings should NOT return a match as no common words exist
"I like sand"
"Ice cream"

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

尝试拆分两个字符串,然后使用LINQ Intersect()获取两个字符串中的拆分,并使用Any()检查是否存在这样的交集:

var first = "I like sand";
var second = "san dune";

var result = first.Split(' ').Intersect(second.Split(' ')).Any();

答案 1 :(得分:1)

我建议在Option Explicit Sub HGScrape() 'Application.ScreenUpdating = False 'we define the essential variables Dim ie As Object Dim my_url As String Dim SearchButton, NameBox, AddressBox Dim ele As Object Dim x As Integer Dim y As Integer Dim IsOdd As Integer Dim html_doc As Object 'HTMLDocument Dim xml_obj As Object 'MSXML2.DOMDocument my_url = "https://www.healthgrades.com/" 'add the "Microsoft Internet Controls" reference in your VBA Project indirectly Set ie = New InternetExplorer ie.Visible = True 'False '''''''''''''''''''''' ie.Navigate my_url '"13.33.74.92" '("https://www.healthgrades.com/") While ie.ReadyState <> 4 DoEvents Wend Set NameBox = ie.Document.getElementById("search-term-selector-child") NameBox.Value = ActiveSheet.Range("A2") Set AddressBox = ie.Document.getElementById("search-location-selector-child") AddressBox.Value = ActiveSheet.Range("B2") Set html_doc = CreateObject("htmlfile") Set xml_obj = CreateObject("MSXML2.XMLHTTP") xml_obj.Open "GET", my_url, False xml_obj.send html_doc.body.innerHTML = xml_obj.responseText Set SearchButton = ie.Document.getElementsByClassName("autosuggest_submiter") 'id of the button control (HTML Control) SearchButton.Click While ie.ReadyState <> 4 DoEvents Wend 上分割而不是空白字符,这样就可以在所有空格上分割。您还可以将其提取为函数:

null

然后您可以这样称呼它:

private static bool CompareStrings(string a, string b)
{
    return a.Split(null).Intersect(b.Split(null)).Any();
}

请记住,此解决方案区分大小写,因此bool result = CompareStrings("I like sand", "sand dune"); bool result2 = CompareStrings("I like sand", "Ice cream"); Sand 不会匹配。

提琴here