title: Editing dictionary values in a foreach loop
body: <p>I am trying to build a pie chart from a dictionary. Before I display the pie chart, I want to tidy up the data. I'm removing any pie slices that would be less than 5% of the pie and putting them in a "Other" pie slice. However I'm getting a <code>Collection was modified; enumeration operation may not execute</code> exception at runtime.</p>
  
  <p>I understand why you can not add or remove items from a dictionary while iterating over them. However I don't understand why you can't simply change a value for an existing key within the foreach loop.</p>
  
  <p>Any suggestions re: fixing my code, would be appreciated.</p>
  
  <pre><code>Dictionary&lt;string, int&gt; colStates = new Dictionary&lt;string,int&gt;();
  // ...
  // Some code to populate colStates dictionary
  // ...
  
  int OtherCount = 0;
  
  foreach(string key in colStates.Keys)
  {
  
      double  Percent = colStates[key] / TotalCount;
  
      if (Percent &lt; 0.05)
      {
          OtherCount += colStates[key];
          colStates[key] = 0;
      }
  }
  
  colStates.Add("Other", OtherCount);
  </code></pre>