title: Anonymous type collections?
body: <p>I am looking for best practices for creating collections made from anonymous types.</p>
  
  <p>There are several approaches - <a href="http://www.eggheadcafe.com/software/aspnet/31356077/using-anonymous-types-in.aspx" rel="nofollow noreferrer">this</a> one and most answers on <a href="http://blog.sb2.fr/post/2008/11/25/Anonymous-Type-Collection-with-C-35.aspx" rel="nofollow noreferrer">this</a> thread assume that the whole anonymous collection can be constructed in one statement.</p>
  
  <p>As anonymous types are usually used to replace classes that are to be used to store temporary (as put forward in <a href="https://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c/48705#48705">this SO answer</a>), I would like to avoid creating and using a class for anonymous collections, as <a href="http://blogs.msdn.com/timng/archive/2007/04/07/making-collections-of-anonymous-types.aspx" rel="nofollow noreferrer">this post</a> suggests.</p>
  
  <p>In my case, I am iterating over a collection - for each item in the collection I would like to collect related objects in an anonymous type (acting as a tuple). I need these anonymous types to be put in a collection and then sort them for further work.</p>
  
  <p>Other approaches I have considered:</p>
  
  <ol>
  <li>Use an object[] or ArrayList (losing the benefit of the anonymous type)</li>
  <li>Creating a wrapper class for the required items (removing the need for the anonymous type)</li>
  </ol>
  
  <p>This is the only place in my code that I need such a collection - what would be the best approach?</p>
  
  <p><strong>Additional Information:</strong></p>
  
  <p>I am working with legacy .Net 1.1 objects, so the collections I am working with are strongly typed collections implementing IEnumerable, and as such most Linq extension methods such as .Select won't work:</p>
  
  <p><strong>Code sample</strong></p>
  
  <pre><code>foreach (Item item in myItems)
  {
      foreach (Confirmation confirmation in item.GetConfirmations(true))
      {
          if (lastParentId != item.ParentId)
          {
              lastParentId = item.ParentId;
              parentObject = new ParentItem(lastParentId);
          }
  
          itemHolder = new ArrayList { item, confirmation };
          if (parentObject!= null)
          {
              itemHolder.Add(parentObject.Rate);
          }
  
          sortConfirmations.Add(confirmation.Date, itemHolder);
      }
  }
  
  // Use sortConfirmations
  </code></pre>
  
  <p><strong>Resolution</strong></p>
  
  <p>I ended up using a generic dictionary to collect the related items together and using .OrderBy() to sort them - ugly, but it works... and is better than the existing code.</p>