Safely Removing DataRow In ForEach

2019-01-22 10:59发布

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

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

15条回答
唯我独甜
2楼-- · 2019-01-22 11:50

Use this:

for (int i = 0; i < myDataTable.Rows.Count; i++)

{

 myDataTable[i].Delete();

}
查看更多
淡お忘
3楼-- · 2019-01-22 11:51
foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}

dataTable.AcceptChanges();

Please Refer the snaps to understatnd the working of it.

  1. Just Deleted but not removed from the DataTable.

enter image description here

  1. Break point before AcceptChanges() Function. enter image description here
  2. After Eexecuting AcceptChanges() Function. enter image description here

I Hope this issue resolved now.

查看更多
神经病院院长
4楼-- · 2019-01-22 11:54

You cannot modify a collection while you're iterating on it using a foreach statement.

you can try something like that :

List<DataRow> deletedRows = new List<DataRow>();

foreach (DataRow dataRow in dataTable.Rows)
{
    if(true) deletedRows.Add(dataRow);
}

foreach(DataRow dataRow in deletedRows)
{
    dataRow.Delete();
}
查看更多
欢心
5楼-- · 2019-01-22 11:56

Where items have a Count, this is what I have done:

int Count = myTable.Rows.Count;

while (Count > 0) // replace condition with myTable.Rows.Count if unconditionally performed on all rows
{
    DataRow row = myTable.Rows[0] // or however you want to find your index

    // do some work
    myTable.Rows.Remove(row);

    // if you want to perform a check to break out of while
    if (someCondition)
        Count = 0;
    else
        Count = myTable.Rows.Count;
}

Note, that where objects have a .GetXXXX() collection, like FileInfo (IIRC), deleting item contents in a foreach is acceptable. One solution I have considered is creating an extension method that provides a .GetItems() method.

查看更多
Bombasti
6楼-- · 2019-01-22 12:00

If you call the delete method you just have to call AcceptChanges() on the table you are modifying, after the foreach loop.

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

dataTable.AcceptChanges();

The delete method simply marks the row for deletion.

http://msdn.microsoft.com/en-us/library/system.data.datarow.delete%28v=VS.90%29.aspx

查看更多
虎瘦雄心在
7楼-- · 2019-01-22 12:00

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.

查看更多
登录 后发表回答