Order text files by title and then by body

75 Views Asked by At

I have a class named TextFile with a Title and Body which are both strings.

In my application I want the end user to be able to perform searches on these files.

I want to create my algorithm that first the files with the search term in the title are ordered first, followed by the files that have the search term in the body.

Example Search term: 'Farmer'

File 1:

Title: 'Farmers in Europe'

Body: contains 'Farmer' 50 times

File 2:

Title: 'Vegetable land'

Body: contains 'Farmer' 10 times

File 3:

Title: 'Farmers in the world'

Body: contains 'Farmer' 10 times

The result would be (ordered by amount descending):

  1. File 1
  2. File 3
  3. File 2

My question: how do I start ordering when files have the search term in the title the exact amount of times (see file 1 and file 3) ?

How would I order by Title first and then by the amount of occurrences in the body?

1

There are 1 best solutions below

0
On

Just write a method like int performSearch(string searchFor, TextFile file).
Inside the method, you search in the fields.
To count the matches use RegEx or look here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-count-occurrences-of-a-word-in-a-string-linq

Just add the counts together and return. You can also define some weights.
As example: return (10 * countTitle) + (countBody);
Now you can sort it in this way: textFileList.OrderBy(file => performSearch(searchValue, file)) and you will get a ordered list of your files.