Emad GabrielThoughts, tips and shortcuts about building software
Tips

Note about the "foreach" enumeration

 

There is a subtle note about using the "foreach" enumeration. The "foreach" uses an enumerator that assumes that the number of elements in the collection will remain intact during the enumeration.

If this changes, an exception "Collection was modified, Enumeration Operation may not execute".

 

what that means is:

you can NOT do something like

foreach(datarow row in table.rows)

{

if (some condition)

{

     table.rows.remove(row);

}

 

trying to remove a row form within the enumeration will throw an exception.

 

 

A better way to do it is :

 

for(int x =  table.rows.count-1; x>=0; x-- )

{

if (some condition)

{

     table.rows.remove(row);

}

Note that the for loop is a decrementing loop (x--) to avoid having problems with the rows position when one or more rows are removed from the collection