BlackICE
BlackICE

Reputation: 8926

Multiple Dynamic Order By in Linq to Entity Framework

Dim receipts As IQueryable(Of ReceiptEntity) = db.Receipts

'code to filter removed for brevity

Dim sorts() As String = SortExpression.Split(";")

For Each sort As String In sorts
    Dim sortParts() As String = sort.Split(" ")
    If sortParts(1).ToLower = "true" Then
        receipts = receipts.OrderBy(Of ReceiptEntity)(sortParts(0).ToString(), SortDirection.Ascending)
    Else
        receipts = receipts.OrderBy(Of ReceiptEntity)(sortParts(0).ToString(), SortDirection.Descending)
    End If
Next

SortExpression comes in like "field1 true;field2 false;field3 true"

What I want to happen is for the query to have multiple order by fields, what is happening is that only the last order by is applied. What am I doing wrong here?


Here is what the working result looks like:

Dim receipts As IOrderedQueryable(Of ReceiptEntity) = db.Receipts.Include(Function(r) r.LineItems).Include(Function(r) r.Payments)

Dim sorts() As String = SortExpression.Split(";")
Dim sortParts() As String
sortParts = sorts(0).Split(" ")
If sortParts(1).ToLower = "true" Then
    receipts = receipts.OrderBy(sortParts(0).ToString())
Else
    receipts = receipts.OrderByDescending(sortParts(0).ToString())
End If


For Each sort As String In sorts.Skip(1)
    sortParts = sort.Split(" ")
    If sortParts(1).ToLower = "true" Then
        receipts = receipts.ThenBy(sortParts(0).ToString())
    Else
        receipts = receipts.ThenByDescending(sortParts(0).ToString())
    End If
Next

Upvotes: 0

Views: 1649

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

You have to use ThenBy instead of OrderBy for the second and all subsequent sort operations.

Upvotes: 1

Related Questions