排序集合,并根据一定的标准排名结果 [英] Sort a collection and rank the result based on certain criteria

查看:113
本文介绍了排序集合,并根据一定的标准排名结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下

var searches = new ObservableCollection<Book>();



搜索包含本书的对象。

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



我想搜索排序通过匹配的字符串。首先,它会检查标题比他们排名基于如何接近从标题开头的搜索字符串。接下来,它会检查说明和搜索字符串是如何接近从`说明的开始出现排名。

I want to sort searches by a matching string. First it checks the Title than rank them based on how close the search string from the beginning of Title. Next it checks Desc and rank them by how close the search string appears from the beginning of the `Desc.

例如,如果我有

1册结果
标题:ABC书名结果
说明:本书的描述1

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

2册结果
标题:书名只有结果
说明:有一个ABC中的描述书2

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

3册结果
标题:书名ABC结果
说明:ABC是在开始

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

因此,让说,搜索的关键字是 ABC ,我想搜索来进行排序,使我得到以下。 ,结果地方更高优先级的项目包含在标题中搜索字符串

So let say the search keyword is ABC, I want searches to be sorted so that I get the following. The result place higher priority to items that contains the search string in the title.

1册结果
标题:ABC书名结果
说明:书名ABC结果$ b:书1

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

3册结果
题目的描述$ b说明:ABC是在开始

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

2册结果
标题:书名只有结果
说明:有一个ABC在书2的描述

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

我如何实现这一目标使用LINQ?

How do I achieve this using LINQ?

推荐答案

由于建议由@M帕特尔和Stefano,我在下面的解决方案到达

Thanks to suggestion by @M Patel and Stefano, I've arrived at the following solution

var sorted = searches.Select(tile => new { TileViewModel = tile, Rank = rankResult(tile, text) })
                    .OrderByDescending(r => r.Rank)
                    .Select(r => r.TileViewModel);

SearchResultsTilesVM = new ObservableCollection<TileViewModel>(sorted);

这把关键词的位置的方法。我添加了额外的点,如果比赛是在标题中。

The method that take the position of the keyword. I added extra point if a match is found in the title.

    private int rankResult(TileViewModel vm, string keyword)
    {
        double rank = 0;

        //Added 100 to give stronger weight when keyword found in title
        int index = vm.Title.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase);

        if (index >= 0 )
        {
            rank = (double)(vm.Title.Length - index) / (double)vm.Title.Length * 100 + 100;
        }         

        int index2 = vm.Information.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase);

        if (index2 >= 0)
        {
            rank += (double)(vm.Information.Length - index2) / (double)vm.Information.Length * 100;
        }

        return Convert.ToInt32(rank);
    }

这篇关于排序集合,并根据一定的标准排名结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆