1

I have a List<IGrouping<string, InvoiceCount>> to check positions in a invoice. It works great but when a Position is already in another Invoice the position should be removed but it will come the exception

"Collection was modified; enumeration operation may not execute."

and I have no idea to solve this

 private static void ValidateInvoices(List<IGrouping<string, InvoiceCount>> invo)
        {
            var validationErrors = new StringBuilder();
            foreach (IGrouping<string, InvoiceCount> invoice in invo)
            {
                for (var line = 1; line < invoice.Count(); line++)
                {
                    if (!invoice.ElementAt(line).IsInSameInvoice(invoice.First()))
                    {
                        validationErrors.Append("Validation error in Invoice" + invoice.Key + " in line " + (line + 1) + Environment.NewLine);
                        if (invo.Contains(invoice))
                            try
                            {
                                invo.Remove(invoice);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                    }
                }
            }
            if (validationErrors.Length > 0)
                throw new Exception(validationErrors.ToString());
        }
BhushanK
  • 1,205
  • 6
  • 23
  • 39
kb_
  • 620
  • 4
  • 21
  • 4
    Possible duplicate of [Collection was modified; enumeration operation may not execute](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – Ghasem Dec 21 '15 at 06:41
  • 3
    Possible duplicate of [C# Collection was modified; enumeration operation may not execute](http://stackoverflow.com/questions/2024179/c-sharp-collection-was-modified-enumeration-operation-may-not-execute) – BhushanK Dec 21 '15 at 06:47

1 Answers1

2

You need to refresh the collection after removing element. Try to change your code like below and see if it works:

Code:

var newList = invo;
foreach (IGrouping<string, InvoiceCount> invoice in invo)
{
       for (var line = 1; line < invoice.Count(); line++)                
       {
           if (YOUR CONDITION HERE)
           {
              newList.Remove(invoice );
              invo= newList;
           }
       }
}

Note: How to modify a collection during iteration

Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
LifeOfPi
  • 625
  • 5
  • 19