Tuesday, June 9, 2015

LINQ prioritize order

I recently faced a scenario of prioritizing search results filtered by LINQ. Here is the scenario:

I have these records in database table:

1. Superman vs Batman
2. Batman
3. Dark night rises - Batman
4. Batman Returns

I want to search all the records having 'batman' text, however the words starting with batman should be displayed first. i.e. the order should be:

1. Batman
2. Batman Returns
...


This can be achieved using this simple LINQ query:

DbContext.Movies.Where(w => w.Name.Contains("batman")).OrderBy(d => d.Name.IndexOf("batman")).ToList();

I've highlighted the key part of the query which sorts the results based on the Index of word "batman". This means, if the word starts with 'batman', the index would be 0 and it would be displayed first.

No comments: