Saturday, October 11, 2014

Collection was modified; enumeration operation might not execute.

Problem:
Iterating through a loop of DataTable.Rows and you try and delete a row and get:
Collection was modified; enumeration operation might not execute.
foreach (DataRow dr in dt.Rows)
{
   if ((int)dr["ID"] > 5)
      dr.Delete();
}


Simplest Solution:
Don't loop on the original collection of Rows, but instead do a Select("") and pull those DataRows into an Array and loop on that.  Now you can Delete() to your heart's content.

foreach (DataRow dr in dt.Select(""))
{
   if ((int)dr["ID"] > 5)
      dr.Delete();
}