How to handle an unknown number of Orders in LINQ2SQL
I'm using LINQ to order some data, but I have zero or more OrderBy
开发者_StackOverflow 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:
IQueryable<MyItem> myItems = dataContext.MyItems;
bool first=true;
foreach (var orderClause in myOrderClauses)
{
if(first)
{
myItems = myItems.OrderBy(orderClause);
first = false;
}
else
myItems = myItems.ThenBy(orderClause);
}
This assumes, that myOrderClauses
is of type IEnumerable<Expression<Func<TSource, TKey>>>
.
精彩评论