Is there a way to write a query in LINQ to return the count of the search terms found in a field(s)
Basically, I want this to work:
var matches = from t in _db.Books
let score = GetScore(t, searchterms)
where score >= 1
orderby score descending
select t;
public static int GetScore(Book b, params string[] searchterms)
{
int count = 0;
foreach (string term in searchterms)
{
if (b.Title.Contains(term))
count++;
}
return count;
}
But, of course, that can’t work.
Can my little GetScore function be translated into LINQ?
Thanks.
EDIT: I would also prefer to have the score accessible. Ideally I will be selecting my results into a SearchResults class (for the View) that would contain some Book info and the Book’s score from the query. To update my query, it’d be something like this:
var matches = from t in _db.Books
let score = GetScore(t, searchterms)
where score >= 1
orderby score descending
select new SearchResult
{
Title = t.Title,
Type = "Book",
Link = "Books/Details/" + t.BookID,
Score = score
};
I’m sorry I wasn’t more clear originally.
You can’t do what you want to do without issuing multiple queries to the database – essentially one per search term. If you are happy to do that, then here is an easy way to do it:
I wrote the
idsto return a list of ids sorted by those that match the most terms first. This was to most closely get the same kind of result that you wanted in your question. I then decided to use aTake(50)to get the top 50 results. You can obviously change this strategy to suit your needs, but you must end up with an array of ids to use in the final query.I hope this helps.
EDIT: based on OP’s edit.
Here’s how to query with the score included: