title: Why does ThenBy raise an exception in the following case?
body: <p>I am using .NET 4.5 and I would like to understand the following:</p>
  
  <p>If I execute this everything works as expected:</p>
  
  <pre><code>  Dim lst = Enumerable.Range(1, 10)
    Dim lstOrdered = lst.OrderBy(Function(i) i Mod 2)
    Dim lst2 = lstOrdered.ThenBy(Function(i) -i)
  </code></pre>
  
  <p>However, the following raises a <code>System.MissingMemberException</code></p>
  
  <pre><code>  Dim lst = Enumerable.Range(1, 10)
    Dim lstOrdered
    lstOrdered = lst.OrderBy(Function(i) i Mod 2)
    Dim lst2 = lstOrdered.ThenBy(Function(i) -i)
  </code></pre>
  
  <p>In the real code, we have to dynamically apply sometimes OrderBy and sometimes OrderByDescending and then dymaically continue with ThenBy and ThenByDescending. That's why I would like to declare it first.</p>
  
  <p>Also note that the production code contains anonymous objects instead of integers.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The following code it's closer to production and I don't seem to manage adapting to the provided answer. It compiles but throws an execution error.</p>
  
  <pre><code>Dim lst = Enumerable.Range(1, 10).Select(Function(i) New With {.a = "foo", .b = i Mod 2, .c = -i})
  Dim lstOrdered As IOrderedEnumerable(Of Object)
  lstOrdered = lst.OrderBy(Function(i) i.b)
  Dim lst2 = lstOrdered.ThenBy(Function(i) i.c)  
  </code></pre>
  
  <p>The error sais the following</p>
  
  <pre><code>Unable to cast object of type 'System.Linq.OrderedEnumerable`2[VB$AnonymousType_3`3[System.String,System.Int32,System.Int32],System.Int32]' to type 'System.Linq.IOrderedEnumerable`1[System.Object]'  
  </code></pre>