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

Ste*_*ald 37 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
Run Code Online (Sandbox Code Playgroud)

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

Gri*_*zly 89

既然你想看看搜索是否包含p的描述中包含的单词,你基本上需要测试搜索中的每个值,如果它包含在p的描述中

result = from p in products
           where search.Any(val => p.Description.Contains(val))
           select p;
Run Code Online (Sandbox Code Playgroud)

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

  • 辉煌!有效.VB语法是:search.Any(Function(n)p.Description.ToLower.Contains(n)) (2认同)

jas*_*son 6

Dim result = From p in products _
             Where search.Any(Function(s) p.Description.Contains(s))
             Select p
Run Code Online (Sandbox Code Playgroud)


Nil*_*iya 5

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

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

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

  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);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用正则表达式将字符串分割成多个单词,并测试单词集合的成员资格(如果将make单词改成a HashSet而不是,这会更快List):

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

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

 // Given:
 // bool HasThoseWords(string sentence) { blah }
 var q = sentences.Where(HasThoseWords);
Run Code Online (Sandbox Code Playgroud)

或放在lambda中:

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

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