Conditional “orderby” sort order in LINQ

前端 未结 9 1280
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 23:28

In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).

Something like this (not valid code):

bool flag;

(from w          


        
9条回答
  •  萌比男神i
    2020-12-05 23:53

    You can even do more complex ordering and still keep it short:

        var dict = new Dictionary() { [1] = "z", [3] = "b", [2] = "c" };
        var condition =  true;
        var result = (condition ? dict.OrderBy(x => x.Key) : dict.OrderByDescending(x => x.Value))
            .Select(x => x.Value);
    

提交回复
热议问题