Home > Mobile >  EF Order query by matched filter
EF Order query by matched filter

Time:02-17

I want to find the way to achieve order prioritization by matched field. For example:

var query = ctx.Set<Article>()
   .Where(e => e.Title == "search query" || e.Content == "search query")
   .OrderBy(???)
   .Take(4);

Is it possible to order the result in such a way that records matched by Title was on top, and entries matched by Content was on bottom. In single query which requests only 4 records from database? like this

Title            Content
------------------------------
search query     other text  
search query     other text
other text       search query 
other text       search query     

CodePudding user response:

Sure it is possible. You just order by conditional expression yielding "priority" based on your match conditions. You need to replicate all except the last condition there though. Something like (pseudo code):

.Where(e => cond1(e) || cond2(e) || ... cond{N-1}(e) || condN(e))
.OrderBy(e => cond1(e) ? 0 : cond2(e) ? 1 : ... cond{N-1}(e) ? N - 1 : N)

With your sample:

string match = "search query";

var query = ctx.Set<Article>()
   .Where(e => e.Title == match || e.Content == match)
   .OrderBy(e => e.Title == match ? 0 : 1) // first by priority
   .ThenBy(e => ...) // then by others if needed
   .Take(4);

CodePudding user response:

You can also combine multiple OrderBy at once like this:

string searchQuery = "search query";
int wantedResults = 4:

var query = ctx.Set<Article>()
   .Where(e => e.Title.Equals(searchQuery) || e.Content.Equals(searchQuery))
   .OrderBy(e => new { e.Title, e.Content })
   .Take(wantedResults);

  • Related