title: Using Skip/Take on a type not know at compile-time
body: <p>I'd like to write a function, that retrieves data from a database table page by page. The goal here is to save memory. This is a part of a validation program that we will be running on our database occasionally to make sure that we have consistent data. Tables could be quite big, so I would not want to load the whole table to memory for doing the validation.</p>
  
  <p>With that in mind I wrote this function:</p>
  
  <pre><code>static IEnumerable&lt;T&gt; RetreivePages&lt;T&gt;(IQueryable&lt;T&gt; query, int count, int pageSize)
  {
      int pages = count / pageSize;
      if (count % pageSize &gt; 0)
      {
          pages++;
      }
      for (int i = 0; i &lt; pages; i++)
      {
          foreach (T item in query.Skip(i * pageSize).Take(pageSize))
          {
              yield return item;
          }
      }
  } 
  </code></pre>
  
  <p>The idea here is that we are only retrieving <code>pageSize</code> rows at a time, so we won't fill memory with all the rows from a table.</p>
  
  <p>Unfortunately that does not work. <code>query.Skip</code> line throws the following exception:</p>
  
  <blockquote>
    <p>The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.</p>
  </blockquote>
  
  <p>Is there any other way to accomplish what I want?</p>
  
  <p><strong>Update</strong></p>
  
  <p>The answers to the question linked as duplicate suggest ordering by a column. <code>.OrderBy</code> would not work here because properties on <code>T</code> are not known inside the function.</p>