gpt4 book ai didi

c# - 对集合进行排序并根据特定条件对结果进行排名

转载 作者:太空狗 更新时间:2023-10-29 17:40:15 26 4
gpt4 key购买 nike

假设我有以下内容

var searches = new ObservableCollection<Book>();

searches 包含书籍对象

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

我想按匹配的字符串对搜索 进行排序。首先,它会检查 Title,然后根据搜索字符串距 Title 开头的距离对其进行排名。接下来它检查 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,我希望对 searches 进行排序,以便获得以下内容。结果将更高的优先级给予标题中包含搜索字符串的项目。

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;
}

这就是说:found in title=10 point, found in desc=5 points, so uo get the most relevant books with higher scores.

关于c# - 对集合进行排序并根据特定条件对结果进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com