Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by "Relevance Values"

Tags:

c#

winforms

I'm working on Windows Forms application. I want to apply a filter on ListView. The requirement was to implement search feature in windows when searching files with a given name in a folder.

It turns out that Windows is using Relevance Values to order found files.

I was thinking, maybe there is a build in solution in .Net for that? If not, is there any C# code for this algorithm that I can use to manually order filtered objects:

var searchFor = "search";
var newList = oldList.Select(x =>x.Contains(searchFor))
                     .OrderBy(x => RelevanceValues(x,searchFor))
                     .ToList(); 
like image 890
Mhd Avatar asked Feb 22 '17 20:02

Mhd


1 Answers

You can search and order by relevance values using LINQ with Regex. Please try below code:

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);
like image 157
csharpbd Avatar answered Nov 01 '22 07:11

csharpbd