Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try to fetch the data (funds data) and filter the results with its balance

but this error appear :

System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'



at <pre> foreach (account_funds f in account_Funds)


What I have tried:

public void loadFunds()
      {


          mrsalesdbEntities DB01 = ConnectionTools.OpenConn();
          var account_Funds = DB01.account_funds.Where(u => u.accfunds_CustodyType == 1 && u.r_branche_ID == BasicVars.Branche).ToList();
          foreach (account_funds f in account_Funds)
          {
              if (trsBalance(f.accfunds_ID) == 0) { account_Funds.Remove(f); }
          }
          account_fundsBindingSource.DataSource = account_Funds;
          NameInput.EditValue = account_Funds.FirstOrDefault().accfunds_ID;

      }


public decimal trsBalance(int ID)
       {
           decimal blc = 0;
           if (ID != 0)
           {
               var DB1 = ConnectionTools.OpenConn();
               var account = DB1.account_items.Where(u => u.accitem_TrsID == ID && u.accitem_TrsType == 0 && u.accitem_AccID == 60);
               decimal debet = Convert.ToDecimal(account.Sum(s => s.accitem_Debit));
               decimal credit = Convert.ToDecimal(account.Sum(s => s.accitem_Credit));
               blc = debet - credit;
           }
           return blc.GetDecimalParts();
       }
Posted
Updated 8-Nov-19 8:22am

You cannot enumerate a collection in a foreach block and modify the collection in the same block.
Usually the solution is to get back to a plain old index iteration, starting from the end of the collection. In clear, change
C#
foreach (account_funds f in account_Funds)
{
   if (trsBalance(f.accfunds_ID) == 0) { account_Funds.Remove(f); }
}
to
C#
for (int i = account_Funds.Count - 1; i > -1; --i)
{
   var f = account_Funds[i];
   if (trsBalance(f.accfunds_ID) == 0) { account_Funds.RemoveAt(i); }
}
 
Share this answer
 
Rather than executing

account_Funds.Remove(f);


keep a collection of all the items you want to remove;

var toRemove = new List<account_funds>();
foreach (account_funds f in account_Funds)
          {
              if (trsBalance(f.accfunds_ID) == 0) { toRemove.Add(f); }
          }


after the foreach loop you can then remove the items in toRemove from account_Funds.
 
Share this answer
 
Another option:
C#
account_Funds.RemoveAll(f => trsBalance(f.accfunds_ID) == 0);
List<T>.RemoveAll(Predicate<T>) Method (System.Collections.Generic) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900