I’m using LINQ to order some data, but I have zero or more OrderBy clauses to apply.
As I don’t know how many order clauses I have, I cannot do:
var myItems = dataContext.MyItems
.OrderBy(i => i.ColumnA)
.ThenBy(i => i.ColumnB)
.ThenBy(i => i.ColumnC)
.ThenBy(i => i.ColumnD)
// etc.
Logically, I need something like:
var myItems = dataContext.MyItems;
foreach (var orderClause in myOrderClauses)
{
myItems = myItems.SubOrderMagicallyBy(orderClause);
}
Obviously this is hopeless, so any ideas would be greatly appreciated.
Why doesn’t it work with the
foreach?You just need to handle the special case of the first order clause:
This assumes, that
myOrderClausesis of typeIEnumerable<Expression<Func<TSource, TKey>>>.