Linq多个位置,排序顺序

时间:2017-11-28 09:33:32

标签: c# linq

我想用linq搜索两个不同字段中的单词的结果集,如果短语在“标题”中,那么我首先想要那些结果然后如果短语在“概要”中我想要那些在标题结果之后。

我理解.Where()和.orderby()+ thenBy()是如何工作的但是如何将它们连接在一起所以顺序依赖于where()?

由于

1 个答案:

答案 0 :(得分:3)

只需按值取决于哪个属性包含短语:

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

如果您想应用更多排序条件,可以使用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 */);

或者,如果您想先按其他条件订购,并在此之后仅应用"短语" -order:

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)