title: Entity SQL Sort Then LINQ to Entities GroupBy Doesn't Return IOrderedQueryable
body: <p><strong>Works:</strong> My UI sends up <a href="http://msdn.microsoft.com/en-us/library/bb399560.aspx" rel="nofollow noreferrer">entity sql</a> sort expressions from a jqGrid to my DAL and then applies some Where clauses that get returned to my service layer. My service layer will then create a PaginatedList object that applies the Skip()..Take() to the IQueryable.
  Example:  </p>
  
  <pre><code>var qry = ((IObjectContextAdapter)DbContext).ObjectContext
  .CreateQuery&lt;TEntity&gt;(entityName)
  .OrderBy(pEntitySQLSort.GetEntitySQL()); 
  //GetEntitySQL() i.e. "it.WorksheetID ASC"
  return qry.Where(p=&gt; pStatus == "blah").Skip(5).Take(10);
  </code></pre>
  
  <p><strong>Doesn't Work:</strong> Applying a GroupBy() then Select() that returns a list of the same type of entities (Worksheet).
  Example:  </p>
  
  <pre><code>var qry = ((IObjectContextAdapter)DbContext).ObjectContext
  .CreateQuery&lt;TEntity&gt;(entityName)
  .OrderBy(pEntitySQLSort.GetEntitySQL());
  
  var qryGrouped = qry.GroupBy(pWorksheet =&gt; pWorksheet.ParticipantID)
  .Select(pGroup =&gt; new {Group = pGroup, LatestWorksheetID = pGroup.Max(pWorksheet =&gt; pWorksheet.WorksheetID)})
  .Select(p =&gt; p.Group.FirstOrDefault(pWorksheet =&gt; pWorksheet.WorksheetID == p.LatestWorksheetID)); 
  
  return qryGrouped.Skip(5).Take(10); //throws exception.
  </code></pre>
  
  <p><strong>Throws NotSupportedException: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.</strong></p>
  
  <p>It seems to me that the first snippet does return an IOrderedQueryable that applies the esql sorting expression but the second snippet does not? Or maybe does GroupBy() remove the ordering of a query/collection ? If this is is the case, and since esql must be applied BEFORE LINQ to Entities, how could I accomplish the sql sorting + LINQ GroupBy ?</p>
  
  <p>Related:<br>
  <a href="https://stackoverflow.com/questions/9025137/when-is-objectquery-really-an-iorderedqueryable">When is ObjectQuery really an IOrderedQueryable?</a><br>
  <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/619db347-bd5c-4786-85ef-8b9baee41af2/#3fbc1d6a-ff48-4337-88c3-f9627d259051" rel="nofollow noreferrer">Why can't we mix ESQL and LINQ TO Entities</a></p>