Search code examples
c#linqsortingpredicatebuilder

Dynamic Sorting with PredicateBuilder


I am using PredicateBuilder to dynamically construct LINQ query as below. I can easily add filter expression usingPredicateBuilder, but I cannot find a way to add dynamic sorting using PredicateBuilder. For example, in code below I would like sort by orderid in an ascending order, but this is decided in a dynamic fashion and not known before hand.

Question : Is it possible to do dynamic sorting using PredicateBuilder, and if yes, then how would that be done? I could not find any suitable method under this class. I could only find System.Linq.Dynamic library suitable for dynamic sorting.

var predicate = PredicateBuilder.True<Orders>();
predicate = predicate.And (o => o.OrderID > 10995);
var ordersFiltered = (from o in Orders select o).Where(predicate);
ordersFiltered.Dump();

Solution

  • PredicateBuilder is there for building predicates, and you're not trying to build a predicate, so no, it won't be able to help you.