title: LINQ Max Date with group by
body: <p>I have a requirement to sort a list by 1) the number of times a distinct item appears and then 2) if the count of two distinct rows is the same, the most recently used date of that group.</p>
  
  <p>My group by function and sorting by count is working without the date:</p>
  
  <pre><code>(from x in data
  group x by new { x.Col1, x.Col2, x.Col3} 
  into g
  let count = g.Count()
  select new
  {
      g.Key.Col1,
      g.Key.Col2,
      g.Key.Col3,
      count
  }).OrderByDescending(x =&gt; x.count)
  </code></pre>
  
  <p>However, I have been unable to successfully add the date sort.  I was trying to add the date column as an aggregate in the group by expression, but that doesn't work.</p>
  
  <pre><code>(from x in data
  group x by new { x.Col1, x.Col2, x.Col3, MaxDate = x.CreatedDateTime.Max()}
  into g
  let count = g.Count()
  select new
  {
      g.Key.Col1,
      g.Key.Col2,
      g.Key.Col3,
      count,
      g.Key.MaxDate
  }).OrderByDescending(x =&gt; x.count).ThenByDescending(x =&gt; x.MaxDate)
  </code></pre>
  
  <p>I get why it doesn't work, I just can't think of another route to add the secondary sort.  Any ideas are appreciated!</p>