Click here to Skip to main content
14,360,161 members
Rate this:
Please Sign up or sign in to vote.
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 9:22am
Rate this:
Please Sign up or sign in to vote.

Solution 2

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
foreach (account_funds f in account_Funds)
{
   if (trsBalance(f.accfunds_ID) == 0) { account_Funds.Remove(f); }
}
to
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); }
}
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

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.
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

Another option:
account_Funds.RemoveAll(f => trsBalance(f.accfunds_ID) == 0);
List<T>.RemoveAll(Predicate<T>) Method (System.Collections.Generic) | Microsoft Docs[^]
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100