In a generic abstract base class I\'m storing a couple of expressions used for ordering:
public Expression> OrderByString { get;
Amy B's answer is great, and I based my own solution on it. So my point is more of an improvement for what I needed, which I am likely to improve upon in time.
public interface IOrderer
{
IOrderedQueryable Apply(IQueryable source);
}
public class OrderBy : IOrderer
{
private Expression> _orderExpr;
public OrderBy(Expression> orderExpr)
{
_orderExpr = orderExpr;
}
public IOrderedQueryable Apply(IQueryable source)
{
return source.OrderBy(_orderExpr);
}
}
public class ThenBy : IOrderer
{
private Expression> _orderExpr;
public ThenBy(Expression> orderExpr)
{
_orderExpr = orderExpr;
}
public IOrderedQueryable Apply(IQueryable source)
{
return ((IOrderedQueryable)source).ThenBy(_orderExpr);
}
}
public class OrderCoordinator
{
public List> Orders { get; private set; } = new List>();
public IQueryable ApplyOrder(IQueryable source)
{
foreach (IOrderer orderer in Orders)
{
source = orderer.Apply(source);
}
return source;
}
public OrderCoordinator OrderBy(Expression> orderByExpression)
{
Orders.Add(new OrderBy(orderByExpression));
return this;
}
// Can add more sort calls over time
public OrderCoordinator ThenBy(Expression> orderByExpression)
{
Orders.Add(new ThenBy(orderByExpression));
return this;
}
}
Specify Coordinator with type:
public OrderCoordinator OrderCoordinator { get; private set; } = new OrderCoordinator();
Specify sort ordering:
OrderCoordinator.OrderBy(e => e.MyStringProperty).ThenBy(e => e.MyIntProperty);
Apply the ordering:
ordered = OrderCoordinator.ApplyOrder(ordered);