Conditional “orderby” sort order in LINQ

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.)

Leave a Comment