In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).
Something like this (not valid code):
bool flag;
(from w
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));