Safely Removing DataRow In ForEach

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

    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();
    
    0 讨论(0)
  • 2020-12-14 00:41

    There is an other version of it (I think an easier) what I just used:

    int i=0;
    while (i < myDataTable.Rows.Count)
    {
        if (condition)  //should it be deleted?
            myDataTable.Rows.RemoveAt(i);
        else
            i++;
    }
    

    This faster.

    0 讨论(0)
  • 2020-12-14 00:47

    Only for people who are looking for specific scenario like me, I needed to shorten time taken, and once some useful infomation is extracted from each row, I excluded the row by marking as deleted.

    Hope this help someone...

    foreach (DataRow dataRow in dataTable.Rows)
    {
        if (dataRow.RowState != DataRowState.Deleted)
        {
            if (your condition here)
            {
                dataRow.Delete();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题