11

I have for-each loop in which the data row is updated so the exception ,Collection was modified; enumeration operation might not execute is generated. any way to fix it? i have seen To-List function but it is not working with data row , here is my code:

foreach (DataRow row in dataTable.Rows) {
  temp = row[0].ToString();
  foreach (DataRow rows in dataTable.Rows) {
    if (temp == rows[0].ToString()) {
      tempdatatable.Rows.Add(row[0],row[1]);
      dataTable.Rows.Remove(rows);
      //Update happens here
    }
    tempdatatable.DefaultView.Sort = "gscitations DESC";
    dataGridView1.DataSource = tempdatatable;
  }
}
4

3 Answers 3

11

You cannot modify collection while enumerating it using Enumerator, which is happening behind the scene of the foreach statement (MDSN link).

One possible way to solve this problem is to collect rows to be deleted in the first enumeration and than remove them in the separate loop like this:

var rowsToDelete = new List<DataRow>();

foreach (DataRow row in dataTable.Rows)
     {
         temp = row[0].ToString();
         foreach (DataRow rows in dataTable.Rows)
         {
             if (temp == rows[0].ToString())
             {
                 tempdatatable.Rows.Add(row[0],row[1]);
                 rowsToDelete.Add(rows);
             }
             tempdatatable.DefaultView.Sort = "gscitations DESC";
             dataGridView1.DataSource = tempdatatable;
         }
     }

rowsToDelete.ForEach( x => dataTable.Rows.Remove(x) );

You can also replace foreach loop with for, but you need to do extra work properly handling the current index while deleting the elements.

1
  • but if i remove that rows after the loop it will not be good, because i have 2.5 lac records if every time it finds match and donot remove it , it will search for it again and again so it will be time taking so i want it to remove the rows which matched
    – mani
    Mar 17, 2013 at 5:10
4

Try this :

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    var tempRow = dataTable.Rows[i];
    var temp = dataTable.Rows[i][0];
    for (int j = 0; j < dataTable.Rows.Count; j++)
    {
        DataRow rows = dataTable.Rows[j];
        if (temp == rows[0].ToString())
        {
            tempdatatable.Rows.Add(tempRow[0], tempRow[1]);
            dataTable.Rows.Remove(rows);      //Update happen here
        }
        tempdatatable.DefaultView.Sort = "gscitations DESC";
        dataGridView1.DataSource = tempdatatable;
    }
}
4
  • not working giving error of datatable in 2nd line, index cant b used with datatable
    – mani
    Mar 17, 2013 at 5:08
  • @mani - fixed, was a typo error! Mar 17, 2013 at 5:16
  • @mani - 2nd & 3rd line are changed Mar 17, 2013 at 5:17
  • 2
    A simpler way to resolve this is to change your dataTable.Rows to a dataTable.Select("") and you don't have to worry about creating for loops. codingcramp.blogspot.com/2014/10/… has a pretty good example.
    – Dan
    Oct 11, 2014 at 22:18
0

I would say that you should make a separate table of entries, and instead of calling datatable.Rows.Remove(rows), add the row "rows" to this other table. Then, whenever row or rows iterates, you run an if statement to check if its been "deleted", i.e., in the list of deleted rows. After the enumeration is over, you can then delete those rows permanently from the table.

EDIT:

Here's the code implementation:

DataTable duplicates = dataTable;
duplicates.Rows.Clear(); /* Produces an empty duplicate of the 
dataTable table to put the duplicates in */
foreach (DataRow row in dataTable.Rows)
{
     if (!duplicates.Rows.Contains(row))
     {    
         temp = row[0].ToString();
         foreach (DataRow rows in dataTable.Rows)
         {
             if (temp == rows[0].ToString()&&!duplicates.Rows.Contains(rows)) //need unique key
             {
                 tempdatatable.Rows.Add(row[0],row[1]);

             }
             tempdatatable.DefaultView.Sort = "gscitations DESC";
             dataGridView1.DataSource = tempdatatable;
         }
    }
}
foreach (DataRow row in duplicates.Rows)
{
    dataTable.Rows.Remove(row);
}

if you don't have a unique key, you can try switching !duplicates.Rows.Contains(/*specific row*/) for duplicates.Rows.IndexOf(/*specific row*/)>0. That should provide an adequate substitute.

1
  • Try this short and simple solution, foreach (DataRow row in dataTable.Select("")) { if (row["TABLE_NAME"].ToString().Contains("FilterDatabase")) dataTable.Rows.Remove(row); }
    – Thamarai T
    Mar 27, 2021 at 7:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.