title: Select single item from each group in multiple groups
body: <p>I have a list (specifically IEnumerable) of items of a specific class:</p>
  
  <pre><code>internal class MyItem
  {
      public MyItem(DateTime timestamp, string code)
      {
          Timestamp= timestamp;
          Code = code;
      }
  
      public DateTime Timestamp { get; private set; }
  
      public string Code { get; private set; }
  }
  </code></pre>
  
  <p>Within this list, there will be multiple items with the same code. Each will have a timestamp, which may or may not be unique.</p>
  
  <p>I'm attempting to retrieve a dictionary of MyItem's (<code>Dictionary&lt;string, MyItem&gt;</code>) where the key is the code associated with the item.</p>
  
  <pre><code>public Dictionary&lt;string, MyItem&gt; GetLatestCodes(IEnumerable&lt;MyItem&gt; items, DateTime latestAllowableTimestamp)
  </code></pre>
  
  <p>Given this signature, how would I retrieve the <code>MyItem</code> with a timestamp closest to, but not after <code>latestAllowableTimestamp</code> for each code?</p>
  
  <p>For example, given the following for input:</p>
  
  <pre><code>IEnumerable&lt;MyItem&gt; items = new List&lt;MyItem&gt;{
      new MyItem(DateTime.Parse("1/1/2014"), "1"),
      new MyItem(DateTime.Parse("1/2/2014"), "2"),
      new MyItem(DateTime.Parse("1/3/2014"), "1"),
      new MyItem(DateTime.Parse("1/4/2014"), "1"),
      new MyItem(DateTime.Parse("1/4/2014"), "2")};
  </code></pre>
  
  <p>If the <code>latestAllowableTimestamp</code> is 1/3/2014, the result would contain only the following items:</p>
  
  <pre><code>Timestamp | Code
  ----------------
  1/3/2014  | 1
  1/2/2014  | 2
  </code></pre>
  
  <p>I can manage to filter the list down to only those timestamps prior to <code>latestAllowableTimestamp</code>, but I don't know linq well enough to pick the most recent for each code and insert it into a dictionary.</p>
  
  <pre><code>var output = items.Where(t =&gt; (t.Timestamp &lt;= latestAllowableTimestamp)).GroupBy(t =&gt; t.Code);
  </code></pre>
  
  <p>At this point, I've ended up with two groups, but don't know how to select a single item across each group.</p>