Conditional “orderby” sort order in LINQ

前端 未结 9 1297
爱一瞬间的悲伤
爱一瞬间的悲伤 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-06 00:07

    If you build the expression incrementally you can do this. Generally easier using expressions rather than comprehension expressions:

    var x = widgets.Where(w => w.Name.Contains("xyz"));
    if (flag) {
      x = x.OrderBy(w => w.property);
    } else {
      x = x.OrderByDescending(w => w.property);
    }
    

    (Assuming the Widget's property is basis of sort since you don't list one.)

提交回复
热议问题