Safely Removing DataRow In ForEach

后端 未结 15 2708
小蘑菇
小蘑菇 2020-12-14 00:14

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

foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}
<         


        
15条回答
  •  [愿得一人]
    2020-12-14 00:23

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

提交回复
热议问题