Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely Removing DataRow In ForEach

I don't understand why this code does not work.

foreach (DataRow dataRow in dataTable.Rows) {     if (true)     {         dataRow.Delete();     } } 
like image 223
Jack Kada Avatar asked Feb 26 '10 12:02

Jack Kada


People also ask

How do I delete DataRow?

There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.


2 Answers

Safest way - use for loop

for (int i = datatable.Rows.Count - 1; i >= 0; i--)  {     if (true)     {         datatable.Rows[i].Delete();     } } 

Don't forget to AcceptChanges to remove all marked rows:

datatable.AcceptChanges(); 
like image 79
VMAtm Avatar answered Oct 02 '22 12:10

VMAtm


Even though DataRow.Delete doesn't modify the state of the collection, Microsoft documentation states that you shouldn't call it while iterating over the collection:

Neither Delete nor Remove should be called in a foreach loop while iterating through a DataRowCollection object. Delete nor Remove modify the state of the collection.

The best solution is usually to create a separate collection (e.g. a List<DataRow>) of items you want to remove, and then remove them after you've finished iterating.

This is also the solution for situations where you want to remove items from a collection, as most collections in .NET don't allow you to change the contents of the collection while you're iterating over it.

like image 24
Jon Skeet Avatar answered Oct 02 '22 14:10

Jon Skeet