Conditional “orderby” sort order in LINQ

前端 未结 9 1273
爱一瞬间的悲伤
爱一瞬间的悲伤 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:11

    You could try something like the following:

    var q = from i in list
             where i.Name = "name"
             select i;
    if(foo)
         q = q.OrderBy(o=>o.Name);
    else
         q = q.OrderByDescending(o=>o.Name);
    
    0 讨论(0)
  • 2020-12-06 00:11

    Here is a more general solution, that can be used for various conditional lambda expressions without breaking the flow of the expression.

    public static IEnumerable<T> IfThenElse<T>(
        this IEnumerable<T> elements,
        Func<bool> condition,
        Func<IEnumerable<T>, IEnumerable<T>> thenPath,
        Func<IEnumerable<T>, IEnumerable<T>> elsePath)
    {
        return condition()
            ? thenPath(elements)
            : elsePath(elements);
    }
    

    e.g.

    var result = widgets
        .Where(w => w.Name.Contains("xyz"))
        .IfThenElse(
            () => flag,
            e => e.OrderBy(w => w.Id),
            e => e.OrderByDescending(w => w.Id));
    
    0 讨论(0)
  • 2020-12-06 00:15

    ...Or do it all in one statement

    bool flag;
    
    var result = from w in widgets where w.Name.Contains("xyz")
      orderby
        flag ? w.Id : 0,
        flag ? 0 : w.Id descending
      select w;
    
    0 讨论(0)
提交回复
热议问题