c# - 按 "Relevance Values"排序

标签 c# winforms

我正在处理 Windows 窗体应用程序。我想在 ListView 上应用过滤器。要求是在搜索文件夹中具有给定名称的文件时在 Windows 中实现搜索功能。

原来Windows使用的是Relevance Values订购找到的文件。

我在想,也许 .Net 中有一个内置的解决方案? 如果没有,是否有此算法的任何 C# 代码可用于手动排序过滤的对象:

var searchFor = "search";
var newList = oldList.Select(x =>x.Contains(searchFor))
                     .OrderBy(x => RelevanceValues(x,searchFor))
                     .ToList(); 

最佳答案

这是一个实现这个的例子。此示例包含带有文件列表的按相关值排序。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;    

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        // textBox1 for search string
        private System.Windows.Forms.TextBox textBox1;
        // listView1 for show result
        private System.Windows.Forms.ListView listView1;
        private System.Windows.Forms.Button button1; 

        public Form1()
        {
            InitializeComponent();
        }   

        class MyListViewItem : ListViewItem
        {
            public int Index { get; set; }
        }  

        private void button1_Click(object sender, EventArgs e)
        {
            List<MyListViewItem> myList = new List<MyListViewItem>();

            // open folder browser to get folder path    
            FolderBrowserDialog result = new FolderBrowserDialog();
            if (result.ShowDialog() == DialogResult.OK)
            {
                // get all file list
                string[] files = Directory.GetFiles(result.SelectedPath);
                foreach (string item in files)
                {
                    // find the relevance value based on search string
                    int count = Regex.Matches(Regex.Escape(item.ToLower()), textBox1.Text.ToLower()).Count;
                    myList.Add(new MyListViewItem() { Text = item, Index = count });
                }
            }

            List<ListViewItem> list = new List<ListViewItem>();
            // add file name in final list with order by relevance value
            foreach (var item in myList.OrderByDescending(m => m.Index).ToList())
            {
                list.Add(new ListViewItem() { Text = item.Text });
            }

            listView1.Items.AddRange(list.ToArray());
        }
    }
}

关于c# - 按 "Relevance Values"排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401247/

相关文章:

c# - 在 linux box 中托管 .net API

c# - 如何更新 app.config.exe 文件运行时中的设置

c# - 什么是 Type.GUID,它与 Type.Equals() 有什么关系?

c# - 如何获取两个地理坐标之间的所有点

c# - 重置在组框中以编程方式创建的标签的值

c# - 点击datagrid View 的按钮列,一封自动邮件将被发送到邮件id

c# - 使用 .NET 远程读取事件日志

c# - 如何读取全局资源文件

C# - 在设计时设置数据绑定(bind)级联组合框

c# - JetBrains Rider C# | Windows 窗体用户界面