LINQ:实体字符串字段包含任何字符串数组

时间:2009-11-18 16:23:05

标签: linq arrays string contains

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

它看起来像这样(结果将是在描述文本中有“mustard OR”泡菜“OR”relish“的任何产品):

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

我已经看过this similar question但无法让它发挥作用。

3 个答案:

答案 0 :(得分:89)

由于您想要查看搜索是否包含p的描述中包含的单词,您基本上需要测试搜索中的每个值(如果它包含在p的描述中)

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

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

答案 1 :(得分:6)

Dim result = From p in products _
             Where search.Any(Function(s) p.Description.Contains(s))
             Select p

答案 2 :(得分:4)

如果您需要检查子字符串,则可以使用简单的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. 将字符串拆分为带有正则表达式的单词,并测试单词集合的成员资格(如果您将单词变为HashSet而不是List,这会更快) :

    var pattern = new Regex(@"\W");
    var q = pattern.Split(myText).Any(w => words.Contains(w));
    
  3. 为了根据这个标准过滤一系列句子,你只需将它放入一个函数并调用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 =&gt; @R How to check if any word in my List<string> contains in text。 Martinho Fernandes