Safely Removing DataRow In ForEach

后端 未结 15 2713
小蘑菇
小蘑菇 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:34

    The Rows content changes while you are iterating if you delete one row, which renders the iteration invalid.

    You can, however, copy the rows into a collection first and then iterate over the collection and delete the rows that way. This makes sure that the iteration is not interrupted by changing data to be iterated.

提交回复
热议问题