我正在开发winforms应用程序。我想在ListView上应用过滤器。当在文件夹中搜索具有给定名称的文件时,要求是在窗口中实现精确搜索功能。
事实证明,Windows正在使用Relevance Values订购找到的文件。
我在想,也许winforms在一个Control或另一个Control中实现了这个算法?或者也许.NET有一些在哪里? 如果没有,是否有可用于手动订购过滤对象的此算法的C#代码:
var searchFor = "search";
var newList = oldList.Select(x =>x.Contains(searchFor))
.OrderBy(x => RelevanceValues(x,searchFor))
.ToList();
答案 0 :(得分:3)
以下是实现此目的的示例。此示例包含“按文件列出的相关值排序”。
CODE:
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());
}
}
}
答案 1 :(得分:2)
您可以使用LINQ和Regex按相关性值进行搜索和排序。请尝试以下代码:
var searchFor = "search";
var newList = oldList.Select(l => new
{
SearchResult = l,
RelevanceValue = (Regex.Matches(Regex.Escape(l.Text.ToLower()), searchFor.ToLower()).Count)
})
.OrderByDescending(r => r.RelevanceValue)
.Select(r => r.SearchResult);