OrderBy IndexOf string with negatives at the bottom

I have a line in my code that sorts a bunch of lines. The items to sort are the result of a database query that returns a bunch of titles, where the search phrase is in the title column and the keywords column. I want to sort them by the first search phrase value, but when the search phrase is not in the title, they have an index of -1 and they end up at the top. I would like to get results that do not include the search phrase in the title at the bottom.

q = "orange";
IQueryable.OrderBy(a => a.title.IndexOf(q));



source to share

1 answer

The problem is what is -1

interpreted as a lower number and so they end up at the beginning of the result. Instead, change -1

(aka not found) to the highest possible number and push the items back

q = "orange";
IQueryable.OrderBy(a => {
  var index = a.title.IndexOf(q);
  return index < 0 ? Int32.MaxValue : index; });




All Articles