title: Iterating over a growing dictionary
body: <p>I am working with C# and I have a dictionary called <code>intervalRecordsPerObject</code> of type <code>Dictionary&lt;string, List&lt;TimeInterval&gt;&gt;</code>. I need to iterate through the dictionary. The problem is: everytime I iterate through the dictionary, more <code>KeyValuePairs</code> may get added to it. As the dictionary grows, I need to keep iterating over the new entries too.</p>
  
  <p>Firstly, I did this: A simple <code>foreach</code> loop that gave me an <code>InvalidOperationException</code> saying </p>
  
  <blockquote>
    <p><code>Collection was modified; enumeration operation may not execute.</code></p>
  </blockquote>
  
  <p>I know I cannot iterate over the Dictionary this way if it keeps changing as C# converts it with <code>ToList()</code> before <code>foreach</code> loop.</p>
  
  <p>I know I can copy the keys to a temporary array, iterate over the dictionary using simple <code>for</code> loop and <code>Count</code> and whenever a new entry is added to the dictionary, add the corresponding key to the array too. Now, the problem is a simple array cannot grow dynamically and I don't know beforehand what the required size could be. </p>
  
  <p>To move ahead, I thought I'd do this:</p>
  
  <pre><code>List&lt;string&gt; keyList = new List&lt;string&gt;(intervalRecordsPerObject.Count);
  intervalRecordsPerObject.Keys.CopyTo(keyList.ToArray(), 0);
  </code></pre>
  
  <p>I cannot do this either. <code>keyList</code> is currently empty and therefore <code>keyList.toArray()</code> returns an array of length 0 which gives me an <code>ArgumentException</code> saying </p>
  
  <blockquote>
    <p><code>Destination array is not long enough to copy all the items in the
    collection. Check array index and length.</code></p>
  </blockquote>
  
  <p>I am stuck! Any idea what more can I try? Thanks for any help.</p>
  
  <h2>Addition 1:</h2>
  
  <p>The dictionary stores the time intervals for which a particular object is present. Key is the ID of the object. New entries may get added in every iteration (worst case) or may not get added even once. Whether or not entries are added is decided by a few conditions (whether the object overlaps with some other intervals, etc.). This triggers a change in the ID and the corresponding interval list which is then added as a new entry to the dictionary. </p>