Conditional “orderby” sort order in LINQ

前端 未结 9 1300
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  天涯浪人
    2020-12-05 23:49

    If the ordering property Id is a number (or supports the unary minus) one could also do:

    bool ascending = ...
    
    collection.Where(x => ...)
      .OrderBy(x => ascending ? x.Id : -x.Id)
      .Select(x => ...)
    
    // LINQ query
    from x in ...
    orderby (ascending ? x.Id : -x.Id)
    select ...
    

提交回复
热议问题