I don't understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
I don't understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
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.There is an other version of it (I think an easier) what I just used:
This faster.
may be my answer not longer useful. exception throw in Foreach with DataRow only appear in .Net 2.0 and earlier, the reason is description at msdn http://msdn.microsoft.com/en-us/library/system.data.datarow.delete(v=vs.80).aspx
If the RowState of the row is Added, the row is removed from the table.
The RowState becomes Deleted after you use the Delete method. It remains Deleted until you call AcceptChanges.
A deleted row can be undeleted by invoking RejectChanges.
to pass this problem you can call DataTable.AcceptChanges() before using foreach
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...
Sure Magents
This is how I did it and works fine
Most collections in .NET don't allow you to change the contents of the collection while you're iterating over it. From the docs for
IEnumerator
:The best solution is usually to create a separate collection (e.g. a
List<DataRow>
) of items you want to remove, and then remove them after you've finished iterating.