title: Entity Framework - Linq query with order by and group by
body: <p>I have <code>Measurement</code> Objects with the relevant Properties <code>CreationTime</code> (DateTime) and <code>Reference</code> (String) and some other values.</p>
  
  <p>I'd like to write an efficient linq query to a <code>DbContext</code> that </p>
  
  <ul>
  <li>groups my <code>Measurement</code> objects by a given <code>Reference</code></li>
  <li>orders the groups by either the <code>CreationTime</code> Property of the first <code>Measurement</code> from the group or the average of the <code>CreationTime</code> properties</li>
  <li>limits the query to the most recent <code>numOfEntries</code></li>
  </ul>
  
  <p>(In a later step i calculate averaged values over these returned groups, but i guess that's not relevant for my problem.)</p>
  
  <p>The DbContext itself has a <code>DbSet&lt;Measurement&gt;</code> called <code>Measurements</code>holding all <code>Measurement</code> objects.</p>
  
  <p>I came up with the following query, that results in a List of groups that is ordered correctly but is missing some groups in between.</p>
  
  <pre><code>var groupByReference = (from m in context.Measurements
                            orderby m.CreationTime
                            group m by new { m.Reference } into g
                            select g).Take(numOfEntries).ToList();
  </code></pre>
  
  <p>How do I select the "most recent" groups of <code>Measurement</code>s correctly?</p>
  
  <p>I'm using Entity Framework 4.4 with a MySQL Database (MySql Connector/Net 6.6.4). This example is simplified, i can go into more detail and/or give an example if necessary.</p>
  
  <p>Thanks!</p>