Conditional “orderby” sort order in LINQ

前端 未结 9 1272
爱一瞬间的悲伤
爱一瞬间的悲伤 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 ...
    
    0 讨论(0)
  • 2020-12-05 23:53

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

        var dict = new Dictionary<int, string>() { [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);
    
    0 讨论(0)
  • 2020-12-05 23:54

    You can define a base query without the ordering, then order according to the flag:

    var query=(from w in widgets
      where w.Name.Contains("xyz")
      select w);
    
    var result = flag ?
      query.OrderBy(w =>w) :
      query.OrderByDescending(w = w);
    
    0 讨论(0)
  • 2020-12-06 00:03
     bool flag;
    
     from w in widgets
     where w.Name.Contains("xyz")
     orderby flag == true ? w.Id : w.Id descending
     select w
    

    ascending is impled

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-06 00:10

    The MoreLINQ NuGet package also provides extension methods to make this more convenient. It also provides many more helpful extension methods and is therefore a stable go-to in my projects.

    0 讨论(0)
提交回复
热议问题