title: Group by and MIN() in LINQ
body: <p>Trying to convert the below SQL query to LINQ, but I'm stuck at grouping by ClientCompany.</p>
  
  <pre><code>SELECT TOP 300 ClientCompany,
  CASE WHEN MIN(FeatureID) = 12 THEN 1 ELSE 0 END as Sort
  FROM Ad
  LEFT JOIN AdFeature
  ON Ad.ID = AdFeature.AdID
  WHERE (AdFeature.FeatureID = 13 OR AdFeature.FeatureID = 12)
  AND SiteID = 2
  GROUP BY ClientCompany
  ORDER BY Sort DESC
  </code></pre>
  
  <p>My attempt to convert this to LINQ:</p>
  
  <pre><code>(from a in Ads
  join af in AdFeatures
  on new {
  join1 = a.ID,
  join3 = 2
  } equals new {
  join1 = af.AdID,
  join3 = af.SiteID
  }
  let sort = (
  af.FeatureID == 12 ? 1 : 0
  )
  orderby sort descending
  where af.FeatureID == 13 || af.FeatureID == 12
  select new { a.ClientCompany, sort } ).Take(300)
  </code></pre>
  
  <p>How would I use <code>MIN(FeatureID)</code> and <code>GROUP BY ClientCompany</code> in LINQ, so that I only get a single row per ClientCompany back?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>This worked! Based on Daniel Hilgarth's answer. Is there anything that can go horribly wrong with this solution?</p>
  
  <pre><code>Ads.Join(AdFeatures, x =&gt; x.ID, x =&gt; x.AdID,
  (a, af) =&gt; new { Ad = a, AdFeature = af })
  .Where(x =&gt; x.AdFeature.FeatureID == 12 || x.AdFeature.FeatureID == 13)
  .Where(x =&gt; x.AdFeature.SiteID == 2)
  .GroupBy(x =&gt; x.Ad.ClientCompany)
  .Select(g =&gt; new { ClientCompany = g.Key, Sort = g.Min(x =&gt; x.AdFeature.FeatureID) == 12 ? 1 : 0 })
  .OrderByDescending(x =&gt; x.Sort)
  .Take(300)
  </code></pre>