Software Development Network>> Visual C#>> Collection was modified; enumeration operation may not execute.
Collection was modified; enumeration operation may not execute.
JWelton
You modify a collection when using an enumerator because when you change the collection while enumerating an exception is thrown.
To solve this problem use a for-loop, or a while with index of. Here are the two examples:
For-loop
for( int i = arraylist.Count - 1; i >= 0; i-- )
{
string currentValue = (string)arraylist[ i ];
if( currentValue.Equals( "del" ) )
{
// TODO: Do delete logic here.
}
}
While-loop
int index = 0;
while( (index = arraylist.IndexOf( "del" )) != -1 )
{
arraylist.RemoteAt( index );
}