I wrote an extension method to try and count the words in a string that appear in a description. Here is the function (for examples sake, searching “soft” I’d want to see Microsoft so calling it keywords may be incorrect, but I wanted to communicate that ahead. Keyword was just the only thing that came to mind at the time):
public static int KeywordCount(this string str, string Phrase)
{
string[] elements = Phrase.ToUpper().Split(' ');
int count = 0;
foreach (string element in elements)
{
if (str.ToUpper().Contains(element))
count++;
}
return count;
}
I’m trying to then go through a list of items and include only the items where at least something hits, but also sorting it based on the number of hits (if all keywords are in the description, it needs to be at the top and so forth.
What I have so far is:
selection.AddRange(all.Where(c => c.Description.KeywordCount(query) > 0));
How can I then sort based on the return value of KeywordCount? I also have a feeling that the direction I’m going will result in doing the KeywordCount search 1x per all items and 1x extra for items with a count > 0, so if there is a way to do the compare and sort at the same time, I’d like to know how.
Do a select to get the value and the count first, then filter on count, then order by the count, then select just the value.
This way the KeywordCount is called once per item.