CerIs
CerIs

Reputation: 567

Linq multiple where with sorted order

I want to search a result set with linq for a word in two different fields, if the phrase is in "Title" then I want those results first and then if the phrase is in "Synopsis" I want those after title results.

I understand how .Where() and .orderby() + thenBy() works but how do you connect them together so the order is dependent on the where()?

Thanks

Upvotes: 1

Views: 51

Answers (1)

René Vogt
René Vogt

Reputation: 43876

Simply order by a value depending on which property contains the phrase:

var orderedResult = result.Where(x => x.Title == phrase || x.Synopsis == phrase)
                          .OrderBy(x => x.Title == phrase ? 1 : 2);

If you want to apply more sort criteria you can use ThenBy:

var orderedResult = result.Where(x => x.Title == phrase || x.Synopsis == phrase)
                          .OrderBy(x => x.Title == phrase ? 1 : 2)
                          .ThenBy(x => /* whatever you want to order by */);

Or if you want to order by another criteria first and apply the "phrase"-order only after that:

var orderedResult = result.Where(x => x.Title == phrase || x.Synopsis == phrase)
                          .OrderBy(x => /* whatever you want to order by */);
                          .ThenBy(x => x.Title == phrase ? 1 : 2)

Upvotes: 3

Related Questions