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());
}