【问题标题】:LINQ: Entity string field contains any of an array of stringsLINQ:实体字符串字段包含任何字符串数组
【发布时间】:2010-12-17 22:49:59
【问题描述】:

我想获取 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

我已经查看了this similar question,但无法使用。

【问题讨论】:

    标签: linq arrays string contains


    【解决方案1】:

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

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

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

    【讨论】:

    • 太棒了!有效。 VB语法为:search.Any(Function(n) p.Description.ToLower.Contains(n))
    • 当我尝试执行此操作时,我得到“无法创建类型为‘闭包类型’的常量值。仅支持原始类型(‘例如 Int32、String 和 Guid’)语境。”我的“搜索”是一个 List,我的“描述”也是一个字符串。
    【解决方案2】:
    Dim result = From p in products _
                 Where search.Any(Function(s) p.Description.Contains(s))
                 Select p
    

    【讨论】:

    • 该死的你偷了我的第一个 VB.NET 答案! ;p +1 反正
    • @leppie:是的,这是我为数不多的 VB.NET 答案之一。
    【解决方案3】:

    如果您只需要检查子字符串,您可以使用简单的 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 为 HashSet 而不是 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 => How to check if any word in my List<string> contains in text @R。马蒂尼奥·费尔南德斯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 2012-02-18
      相关资源
      最近更新 更多