'foreach' isn't such a simple answer to this question either -- you run into the problem where the enumerator is no longer valid for a changed collection.
The hassle here is that the Delete() behavior is different for a row in DataRowState.Added vs. Unchanged or Modified. If you Delete() an added row, it does just remove it from the collection since the data store presumably never knew about it anyway. Delete() on an unchanged or modified row simply marks it as deleted as others have indicated.
So I've ended up implementing an extension method like this to handle deleting all rows. If anyone has any better solutions, that would be great.
public static void DeleteAllRows(this DataTable table)
{
int idx = 0;
while (idx < table.Rows.Count)
{
int curCount = table.Rows.Count;
table.Rows[idx].Delete();
if (curCount == table.Rows.Count) idx++;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…