title: Error: Collection was modified; enumeration operation may not execute
body: <p>I've been getting this exception out in the field. I don't understand how the collection can be modified while iterating. I copy everything to local variables at the start of the method.</p>
  
  <pre><code>  public void Flush() {
              var tempEntities = attachedEntities.Select(item =&gt; item).ToList();
              attachedEntities.Clear();
  
              var tempEntitiesToDelete = entitiesToDelete.Select(item =&gt; item).ToList();
              entitiesToDelete.Clear();
  
              foreach (var attachedEntity in tempEntities) {
                  var isTransient = (bool)GetPrivateField(attachedEntity.GetType(), attachedEntity, "isTransient");
                  if (isTransient)
                      db.Insert(attachedEntity);
                  else
                      db.Update(attachedEntity);
              }
  
              foreach (var entity in tempEntitiesToDelete)
                  db.Delete(entity);
          }
  </code></pre>
  
  <p>Stack Trace</p>
  
  <pre><code>System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
    at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].VerifyState () [0x00000] in &lt;filename unknown&gt;:0 
    at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in &lt;filename unknown&gt;:0 
    at System.Linq.Enumerable &lt;CreateSelectIterator&gt;c__Iterator1D`2[Compass.Mobile.Core.DataAccess.IEntity,Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in &lt;filename unknown&gt;:0 
    at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in &lt;filename unknown&gt;:0 
    at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity]..ctor (IEnumerable`1 collection) [0x00000] in &lt;filename unknown&gt;:0 
    at System.Linq.Enumerable.ToList[TSource] (IEnumerable`1 source) [0x00000] in &lt;filename unknown&gt;:0 
    at Compass.Mobile.Core.DataAccess.Session.Flush () [0x00000] in &lt;filename unknown&gt;:0 
    at Compass.Mobile.Core.DataAccess.Session.Commit () [0x00000] in &lt;filename unknown&gt;:0 
    at Compass.Mobile.Core.Bootstrap.CommandBus.Flush () [0x00000] in &lt;filename unknown&gt;:0 
  </code></pre>