根据单词在字符串中出现的次数对列表进行排序

本文关键字:列表 排序 单词 字符串 | 更新日期: 2023-09-27 18:30:22

我有一个列表,它是

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

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

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
    }

任何帮助都非常感谢

根据单词在字符串中出现的次数对列表进行排序

试试这个:-

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

工作小提琴。

您可以使用以下代码和 NinjaNye.SearchExtensions nuget 包执行此操作

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

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