I have few sentences inside my new List(file.txt). Example:
- Walt Disney refused to allow Alfred Hitchcock to film at Disneyland in the early 1960s because he had made “that disgusting movie Psycho.
- Pumbaa in The Lion King was the first character to fart in a Disney movie.
- Walt Disney paid the animators on Snow White and the Seven Dwarfs $5 for any gag that made it into the final version of the movie.
- The cake in the movie Sixteen Candles is made of cardboard.
etc.
I want to display in my listBox only these sentences which contains any of words entered in search box.Example: When i enter "disney seven dwarfs", it should display "Walt Disney paid the animators on Snow White and the Seven Dwarfs $5 for any gag that made it into the final version of the movie." on the top of the list. It shouldn't display "The cake in the movie Sixteen Candles is made of cardboard.", because this sentence does not contain any of entered words. In brief: on the top should be displayed the result with the highest number of matching words.
public static IEnumerable<string> SplitSearchWords(string str)
{
int charIndex = 0;
int wordStart = 0;
while (charIndex < str.Length)
{
wordStart = charIndex;
if (char.IsLetterOrDigit(str[charIndex]))
{
while (charIndex < str.Length && char.IsLetterOrDigit(str[charIndex])) charIndex++;
yield return str.Substring(wordStart, charIndex-wordStart);
}
else
{
while (charIndex < str.Length && !char.IsLetterOrDigit(str[charIndex])) charIndex++;
}
}
}
public static int CalculateSearchRelevance(string searchItem, IEnumerable<string> searchWords)
{
var searchItemWords = SplitSearchWords(searchItem);
return searchWords.Intersect(searchItemWords, StringComparer.OrdinalIgnoreCase).Count();
}
var myFile = File.ReadAllLines("file.txt");
var myList = new List<string>(myFile);
var query = textBox1.Text;
var items = myList;
var searchWords = SplitSearchWords(query).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var sortedItems = items.OrderByDescending(s => CalculateSearchRelevance(s, searchWords)).ToList();