C# · 12月 29, 2021

c# – 对集合进行排序,并根据某些标准排列结果

说我有以下 var searches = new ObservableCollection<Book>();

搜索包含书籍对象

public class Book{ public string Title { get; set;} public string Desc {get; set;} }

我想通过匹配的字符串对搜索进行排序.首先,它根据标题开头的搜索字符串的距离,对标题进行排序.接下来,它检查Desc,并按照“Desc”开头的搜索字符串的出现距离进行排序.

例如,如果我有

Book 1
Title: ABC Book Title
Desc: The description of book 1

Book 2
Title: Book Title Only
Desc: There’s an ABC in the description of book 2

Book 3
Title: Book Title ABC
Desc: ABC is in the beginning

所以让我们说搜索关键字是ABC,我希望搜索被排序,以便我得到以下内容.结果将标题中包含搜索字符串的项目的优先级更高.

Book 1
Title: ABC Book Title
Desc: The description of book 1

Book 3
Title: Book Title ABC
Desc: ABC is in the beginning

Book 2
Title: Book Title Only
Desc: There’s an ABC in the description of book 2

如何使用LINQ实现这一点?

解决方法 您可以使用排名函数为每本书定义“分数”,然后按分数排序.

var searchString = “ABC”;var results = books.Select(b => new { Book = b,Rank = RankBook(b,searchString) }) .OrderBy(r => r.Rank) .Select(r => r.Book.Title);

而排名功能:

private int RankBook(Book b,string searchString){ int rank = 0; if (b.Title.Contains(searchString)) rank += 10; if (b.Desc.Contains(searchString)) rank += 5; return rank;}

这就是说:发现在title = 10点,发现在desc = 5分,所以你得到更高分数的最相关的书.