Search code examples
c#ado.netdatatablecollectionsdatarow

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();
    }
}

Solution

  • 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.