38

我想获取 Product 实体的集合,其中 product.Description 属性包含字符串数组中的任何单词。

它看起来像这样(结果将是在描述文本中包含“芥末或“泡菜”或“津津有味”一词的任何产品):

Dim products As List(Of ProductEntity) = New ProductRepository().AllProducts

Dim search As String() = {"mustard", "pickles", "relish"}

Dim result = From p In products _
     Where p.Description.Contains(search) _
     Select p

Return result.ToList

我已经看过这个类似的问题,但无法让它发挥作用。

4

3 回答 3

93

由于您想查看 search 是否包含 p 的描述中包含的单词,因此您基本上需要测试 search 中的每个值是否包含在 p 的描述中

result = from p in products
           where search.Any(val => p.Description.Contains(val))
           select p;

这是 lambda 方法的 c# 语法,因为我的 vb 不是那么好

于 2009-11-18T16:27:24.060 回答
6
Dim result = From p in products _
             Where search.Any(Function(s) p.Description.Contains(s))
             Select p
于 2009-11-18T16:24:37.397 回答
5

如果您只需要检查子字符串,则可以使用简单的 LINQ 查询:

var q = words.Any(w => myText.Contains(w));
// returns true if myText == "This password1 is weak";

如果要检查整个单词,可以使用正则表达式:

  1. 匹配作为所有单词析取的正则表达式:

    // you may need to call ToArray if you're not on .NET 4
    var escapedWords = words.Select(w => @"\b" + Regex.Escape(w) + @"\b");
    // the following line builds a regex similar to: (word1)|(word2)|(word3)
    var pattern = new Regex("(" + string.Join(")|(", escapedWords) + ")");
    var q = pattern.IsMatch(myText);
    
  2. 使用正则表达式将字符串拆分为单词,并测试单词集合的成员资格(如果您使用 make words into aHashSet而不是 a ,这将变得更快List):

    var pattern = new Regex(@"\W");
    var q = pattern.Split(myText).Any(w => words.Contains(w));
    

为了根据此标准过滤句子集合,您只需将其放入函数中并调用Where

 // Given:
 // bool HasThoseWords(string sentence) { blah }
 var q = sentences.Where(HasThoseWords);

或者把它放在一个 lambda 中:

 var q = sentences.Where(s => Regex.Split(myText, @"\W").Any(w => words.Contains(w)));

Ans From =>如何检查我的 List<string> 中的任何单词是否包含在@R 的文本中。马蒂尼奥费尔南德斯

于 2013-07-12T09:22:35.677 回答