Conditional “orderby” sort order in LINQ

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

    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 IfThenElse(
        this IEnumerable elements,
        Func condition,
        Func, IEnumerable> thenPath,
        Func, IEnumerable> 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));
    

提交回复
热议问题