I have the below code. I am trying to remove the record and it is throwing Exception when it is removing the Record.
“Collection was modified; enumeration operation may not execute.”
Any ideas on how to get rid of the message. Appreciate your time.
//validClaimControlNo has valid ClaimControl Numbers.
List<string> validClaimControlNo = new List<string>();
int count = 0;
foreach (List<Field> f in records)
{
foreach (Field fe in f)
{
if (i == 0)
if (!(validClaimControlNo.Contains(fe.Value)))
{
//if this claim is not in the Valid list, Remove that Record
records.RemoveAt(count);
}
i++;
}
i = 0;
count++;
}
You cant remove items from a collection you are iterating. Adding
.ToList()will create a new list and thus make it work.An alternative is to iterate the collection backwards (and you wont need the additional list):
But looking at your code it can be simplified great deal: