【问题标题】:Split two strings into List<string> and compare using Linq将两个字符串拆分为 List<string> 并使用 Linq 进行比较
【发布时间】:2019-04-06 02:48:30
【问题描述】:

我有一个对象列表,其中包含一个名为“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 查询,我只能找到完全匹配。因此,假设我的对象颜色属性等于“沙”,查询将返回匹配项,但如果我的颜色等于“沙丘”之类的两个单词名称,我的查询将不会返回匹配项。

这个例子应该有助于解释什么需要作为匹配返回。

//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"

感谢任何帮助。

【问题讨论】:

  • 使用Intersect()Any()

标签: c# linq


【解决方案1】:

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

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

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

【讨论】:

  • 这行得通,谢谢!我之前尝试过 Intersect,但一定是用错了。
【解决方案2】:

我建议拆分 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");

请记住,此解决方案将区分大小写,因此 Sandsand 不会匹配。

小提琴here

【讨论】:

  • 感谢您的回答和关于“null”拆分的建议我给了 Adrian 答案,因为看起来他是第一个加入的。一如既往的好建议,尽管谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-06-09
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多