Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem removing row in datatable while enumerating

Tags:

c#

datatable

I get the following error while I try to delete a row while looping through it.

C#: Collection was modified; enumeration operation may not execute

I've been doing some research for a while, and I've read some similar posts here, but I still haven't found the right answer.

foreach (DataTable table in JobsDS.Tables)
{

  foreach (DataRow row in table.Rows)
  {
    if (row["IP"].ToString() != null && row["IP"].ToString() != "cancelled")
    {
        string newWebServiceUrl = "http://" + row["IP"].ToString() + "/mp/Service.asmx";
        webService.Url = newWebServiceUrl;
        string polledMessage = webService.mpMethod(row["IP"].ToString(), row["ID"].ToString());

        if (polledMessage != null)
        {
            if (polledMessage == "stored")
            {               
                removeJob(id);
            }

        }
    }
}

}

any help would be greatly appreciated

like image 420
hikizume Avatar asked Dec 15 '10 16:12

hikizume


2 Answers

Instead of using foreach, use a reverse for loop:

for(int i = table.Rows.Count - 1; i >= 0; i--)
{
    DataRow row = table.Rows[i];
    //do your stuff
}

Removing the row indeed modifies the original collection of rows. Most enumerators are designed to explode if they detect the source sequence has changed in the middle of an enumeration - rather than try to handle all the weird possibilities of foreaching across something that is changing and probably introduce very subtle bugs, it is safer to simply disallow it.

like image 118
Rex M Avatar answered Sep 27 '22 22:09

Rex M


You cannot modify a collection inside of a foreach around it.

Instead, you should use a backwards for loop.

like image 23
SLaks Avatar answered Sep 27 '22 22:09

SLaks