title: Collection was modified; enumeration operation may not execute during select
body: <blockquote>
    <p>Unhandled exception has occurred. System.InvalidOperationException: Collection was modified; enumeration operation may not execute.<br>
        at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource
    resource)<br>
        at System.Collections.Generic.List`1.Enumerator.MoveNextRare()<br>
        at System.Collections.Generic.List`1.Enumerator.MoveNext()<br>
        at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()<br>
        at System.Linq.Enumerable.Sum(IEnumerable`1 source)<br>
        at Check.get_TotalChange()<br>
        at CheckChanged(ICheck check)</p>
  </blockquote>
  
  <p>If I run my code like 5 thousand times per day like 2 times it will result in this error and the program will crash.. What's wrong with my code? I followed the exception information and I think this is the code that may cause the exception. Anyone have an idea what kind of problem that is?</p>
  
  <pre><code>public decimal TotalChange
  {
      get
      {
          var change = (from IPayment payment in _payments where payment.Amount &lt; 0 select payment.Amount).Sum();
          var paid = (from IPayment payment in _payments select payment.Amount).Sum();
          return paid &lt;= Total &amp;&amp; Total &gt; 0 ? Math.Abs(change) : paid - Total;
      }
  }
  </code></pre>
  
  <p>I changed it up to:</p>
  
  <pre><code>    private readonly object _totalChangeLock = new object();
      public decimal TotalChange
      {
          get
          {
              lock (_totalChangeLock)
              {
                  var change =
                      (from IPayment payment in _payments where payment.Amount &lt; 0 select payment.Amount).Sum();
                  var paid = (from IPayment payment in _payments select payment.Amount).Sum();
                  return paid &lt;= Total ? Math.Abs(change) : paid - Total;
              }
          }
      }
  </code></pre>
  
  <p>Also I do have 2 methods that modify _payments. I locked them too. Hope that doesn't cause any issues.</p>
  
  <pre><code>    public void AddPayment(IPayment payment)
      {
          lock (_paymentsLock)
          {
              if (_payments.Contains(payment)) return;
              _payments.Add(payment);
          }
      }
  
      public void RemovePayment(IPayment payment)
      {
          lock (_paymentsLock)
          {
              if (_payments.Contains(payment))
                  _payments.Remove(payment);
          }
      }
  </code></pre>