title: "Most popular" GROUP BY in LINQ?
body: <p>Assuming a table of tags like the stackoverflow question tags:</p>
  
  <blockquote>
    <p>TagID (bigint), QuestionID (bigint), Tag (varchar)</p>
  </blockquote>
  
  <p>What is the most efficient way to get the 25 most used tags using LINQ?  In SQL, a simple GROUP BY will do:</p>
  
  <pre><code>SELECT Tag, COUNT(Tag) FROM Tags GROUP BY Tag
  </code></pre>
  
  <p>I've written some LINQ that works:</p>
  
  <pre><code>var groups = from t in DataContext.Tags
               group t by t.Tag into g
               select new { Tag = g.Key, Frequency = g.Count() };
  return groups.OrderByDescending(g =&gt; g.Frequency).Take(25);
  </code></pre>
  
  <p>Like, really?  Isn't this mega-verbose?  The sad thing is that I'm doing this to save a massive number of queries, as my Tag objects already contain a Frequency property that would otherwise need to check back with the database for every Tag if I actually used the property.</p>
  
  <p>So I then parse these anonymous types <em>back</em> into Tag objects:</p>
  
  <pre><code>groups.OrderByDescending(g =&gt; g.Frequency).Take(25).ToList().ForEach(t =&gt; tags.Add(new Tag()
  {
      Tag = t.Tag,
      Frequency = t.Frequency
  }));
  </code></pre>
  
  <p>I'm a LINQ newbie, and this doesn't seem right.  Please show me how it's really done.</p>