Note that there are some explanatory texts on larger screens.

plurals
  1. POLinq query with multiple OrderBy statements added in a loop
    primarykey
    data
    text
    <p>I have a method in a webservice that has parameter with which users can decide how they want to order their results. This is a <code>List(Of String)</code> with the names of the fields in the order they want to sort them.</p> <p>I know I can normally order on multiple columns by doing the following</p> <pre><code>Dim test = Bars.OrderBy(Function(x) x.Foo) _ .ThenBy(Function(x) x.Bar) _ .ThenBy(Function(x) x.Test) </code></pre> <p>However in this case this won't work since I can't chain the <code>ThenBy</code> function because I'm adding the sorting orders in a loop. To use <code>ThenBy</code> I need an <code>IOrderedQueryable</code> collection. This is how I would want it to work</p> <pre><code>Dim sortColumns = {"Foo", "Bar", "Test"} Dim query = From b in Bars For each column in sortColumns Select Case column Case "Foo" query = query.Orderby(Function(x) x.Foo) Case "Bar" query = query.Orderby(Function(x) x.Bar) Case "Test" query = query.Orderby(Function(x) x.Test) End Select Next Dim result = query.Select(Function(x) x.x).ToList() Return result </code></pre> <p>This of course won't work because <code>OrderBy</code> will replace any previous ordering. The only solution I can think of is ordering the list on some other variable first so I already have an <code>IOrderedQueryable</code> collection but this just seems like the wrong approach.</p> <pre><code>Dim bars As New List(Of Bar) Dim sortColumns = {"Foo", "Bar", "Test"} Dim query = bars.Select(Function(x) New With {.Temp = 1, .x = x}) _ .OrderBy(Function(x) x.Temp) For Each column In sortColumns Select Case column Case "Foo" query = query.ThenBy(Function(x) x.x.Foo) Case "Bar" query = query.ThenBy(Function(x) x.x.Bar) Case "Test" query = query.ThenBy(Function(x) x.x.Test) End Select Next Dim result = query.Select(Function(x) x.x).ToList() Return result </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload