【问题标题】:Extension of StartsWith that searches in all words搜索所有单词的 StartsWith 扩展
【发布时间】:2013-03-21 06:35:35
【问题描述】:

是否有字符串的 StartsWith 扩展,它在字符串中每个单词的开头进行搜索?

类似: "Ben Stiller".StartsWithExtension("Sti") 返回真

我想要这个,所以我可以为搜索做一个谓词。

假设有一个名为 Persons 的列表,ICollection<Person>
每个人都有一个属性名称,其值类似于“Ben Stiller”或“Adam Sandler”。

我希望能够做如下谓词:

Persons.Where(p => p.Name.StartsWithExtension(query))

谢谢 (欢迎使用其他更好的方法来实现)

【问题讨论】:

  • 如果姓氏有其自身的含义 - 在这种情况下,您想通过它进行搜索/过滤 - 将名称拆分为 2 个属性 - 名字和姓氏(以及可能是全名,以便于打印/记录或您对 person 对象所做的任何事情)
  • 嗯,最简单(即使它不是“最好”)的方法可能是Contains(" " + str);...
  • if (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) return true;
  • 您需要将它与 Linq-to-Sql 或 Linq-to-Entities 一起使用吗?
  • @p.s.w.g 无论哪种方式,这都行不通:该方法无法转换为 SQL。它只适用于 linq to objects。

标签: c# linq search autosuggest startswith


【解决方案1】:

你可以先按单词拆分字符串,像这样:

var result = "Ben Stiller".Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                          .Any(x => x.StartsWith("Sti"));

当然你可以把它写成你自己的扩展方法,像这样:

public static bool AnyWordStartsWith(this string input, string test)
{
    return input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                .Any(x => x.StartsWith(test));
}

【讨论】:

    【解决方案2】:

    可能最简洁的方法是使用正则表达式:

    public static bool StartsWithExtension(this string value, string toFind)
    {
        return Regex.IsMatch(value, @"(^|\s)" + Regex.Escape(toFind));
    }
    

    这也比在字符 ' ' 上拆分源字符串更可靠,因为它可以处理其他空白字符。

    【讨论】:

    • 此外,由于 bcl 正则表达式中固有的伪缓存,您可能会看到重复查询的性能提升(那里的赃物)
    【解决方案3】:

    为什么不创建一个“ToWords”方法,然后将其结果提供给 StartsWith?

    事实上,“ToWords”已经有点存在了:

    编辑:为了咯咯笑,让我们让它在倍数上工作

     var someNames = new []{ "Sterling Archer", "Cyril Figgus" };
     var q = someNames
        .Select(name => name.Split(' '))
        .SelectMany( word => word)
         // the above chops into words
        .Where(word => word.StartsWith("Arch"));
    

    【讨论】:

      【解决方案4】:

      你甚至可以这样检查:

      bool flag = (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) 
      

      【讨论】:

        【解决方案5】:
            public static bool ContainsWordStartingWith(this string aString, string startingWith)
            {
                return aString.Split(' ').Any(w => w.StartsWith(startingWith));
            }
        

        【讨论】:

          猜你喜欢
          • 2022-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-23
          • 2014-07-04
          • 2021-10-25
          • 1970-01-01
          相关资源
          最近更新 更多