title: LINQ Using Max() to select a single row
body: <p>I'm using LINQ on an IQueryable returned from NHibernate and I need to select the row with the maximum value(s) in a couple of fields. </p>
  
  <p>I've simplified the bit that I'm sticking on. I need to select the one row from my table with the maximum value in one field.</p>
  
  <pre class="lang-cs prettyprint-override"><code>var table = new Table { new Row(id: 1, status: 10), new Row(id: 2, status: 20) }
  
  from u in table
  group u by 1 into g
  where u.Status == g.Max(u =&gt; u.Status)
  select u
  </code></pre>
  
  <p>This is incorrect but I can't work out the right form.</p>
  
  <p>BTW, what I'm actually trying to achieve is approximately this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>var clientAddress = this.repository.GetAll()
      .GroupBy(a =&gt; a)
      .SelectMany(
              g =&gt;
              g.Where(
                  a =&gt;
                  a.Reference == clientReference &amp;&amp; 
                  a.Status == ClientStatus.Live &amp;&amp; 
                  a.AddressReference == g.Max(x =&gt; x.AddressReference) &amp;&amp; 
                  a.StartDate == g.Max(x =&gt; x.StartDate)))
      .SingleOrDefault();
  </code></pre>
  
  <p>I started with the above lambda but I've been using LINQPad to try and work out the syntax for selecting the Max().</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Removing the GroupBy was key.</p>
  
  <pre class="lang-cs prettyprint-override"><code>var all = this.repository.GetAll();
  
  var address = all
              .Where(
                  a =&gt;
                  a.Reference == clientReference &amp;&amp; 
                  a.Status == ClientStatus.Live &amp;&amp; 
                  a.StartDate == all.Max(x =&gt; x.StartDate) &amp;&amp;
                  a.AddressReference == all.Max(x =&gt; x.AddressReference))
              .SingleOrDefault();
  </code></pre>