Safely Removing DataRow In ForEach

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

    This is because it looks like try to disassemble the stair of staircase that you climb. Simply, you cannot remove an item you iterate.

    Therefore you should use different array to iterate and remove them from datatable Rows property.

    foreach (DataRow dataRow in dataTable.Select())
    {
        if (true)
        {
            dataTable.Rows.Remove(dataRow);
        }
    }
    

提交回复
热议问题