I'm building a Spec Evaluator which must consider multiple possible OrderBy, as in the next example:
if (spec.Order != null)
{
var count = spec.Order.Count;
if (count == 1)
{
query = query.OrderBy(spec.Order[0]);
}
else if (count == 2)
{
query = query.OrderBy(spec.Order[0])
.ThenBy(spec.Order[1]);
}
else if (count == 3)
{
query = query.OrderBy(spec.Order[0])
.ThenBy(spec.Order[1])
.ThenBy(spec.Order[2]);
}
// And so on...
}
Query
is an IQueryable
, spec.Order
is a list of clauses: List<Expression<Func<T, object>>>
.
I know that I can use an OrderBy with all the clauses passed as string. And I guess I can just project all the Order
clauses to a new string comma-separated. But that solution doesn't seem clean.
Is there any other way to dynamically generate one new ThenBy
for every item of the Order
list, above 1?