I have the following query which works great:
string[] Words = {"search","query","example"};
... Snip ...
var Results = (
from a in q
from w in Words
where
(
a.Title.ToLower().Contains(w)
|| a.Body.ToLower().Contains(w)
)
select new
{
a,
Count = 0
}).OrderByDescending(x=> x.Count)
.Distinct()
.Take(Settings.ArticlesPerPage);
What I need it to do, is return Count which is the total occurrences of the words. I’m going to weight it in favour of the title as well, example:
Count = (OccuranceInTitle * 5) + (OccurancesInBody)
I’m assuming I need to use the Linq.Count but I’m not sure how to apply it in this instance.
This is what I came up with:
Counting occurrences is done with the (surprisingly) quick and dirty method of replacing occurrences with
string.Emptyand calculating based on the resulting string length. After the scores for each article and each word are calculated, I ‘m grouping for each article, ordering by the sum of scores for all the words and taking a chunk out of the results.I didn’t fire up the compiler, so please excuse any obvious mistakes.
Update: This version uses regexes as in
instead of the original version’s
so that it now matches only whole words (the
string.Replaceversion would also match word fragments).