【问题标题】:Sort the List based on number of times a word appear in the string根据单词在字符串中出现的次数对列表进行排序
【发布时间】:2014-11-18 06:59:37
【问题描述】:

我有一个列表

IEnumerable<RSPCA.LIB.Models.Search.SearchItem> results = 
newList<LIB.Models.Search.SearchItem>();

我的 searchItem 类有一个名为 content 的字符串字段。所以基本上我想根据特定字符串(术语)在内容字符串中出现的次数对列表进行排序。 所以假设我的术语是“abc”,所以如果列表的内容字段中的一项包含“abc”两次,另一项包含“abc”3 次,我希望该项在包含它两次的项之前。所以基本上是根据 Occurrence 对列表进行排序。我还在这里粘贴了我的搜索项类:

public class SearchItem : SearchResultItem
{

    public string PageTitle { get; set; }
    public string PageDescription { get; set; }
    public string content {get; set;} // That's the one which I want to use
    }

非常感谢任何帮助

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    试试这个:-

    var result = items.OrderByDescending(x => Regex.Matches(x.content,"abc").Count);
    

    工作Fiddle

    【讨论】:

      【解决方案2】:

      您可以使用以下代码和NinjaNye.SearchExtensions nuget 包来完成此操作

      var results = items.Search(x => s.content)
                         .Containing("abc")
                         .ToRanked()
                         .OrderByDescending(x => x.Hits)
                         .Select(x => x.Item);
      

      如果在您的实现中很重要,这应该比正则表达式实现快得多

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-30
        • 2022-10-23
        • 2013-02-26
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多