I have a DataSet dsComponents
that embraces many tables, all of them are only in-memory, I don't sync them with any database. At some moments I need to remove all rows to free some memory but the function seems not to working (based on this answer)
if(dsComponents.Tables.Contains("MemoryHistory"))
{
dsComponents.Tables["MemoryHistory"].Rows.Clear();
}
But if I break right after this code it shows that there still all rows in the table. I also tried:
if(dsComponents.Tables.Contains("MemoryHistory"))
{
lock(dsComponents.Tables["MemoryHistory"])
{
foreach (DataRow row in dsComponents.Tables["MemoryHistory"].Rows)
{
row.Delete();
}
}
dsComponents.Tables["MemoryHistory"].Rows.Clear();
}
and this one fails with "Collection was modified; enumeration operation may not execute", even with the lock
. So, how to clear the rows of the table but preserve the table itself (like its Primary key, etc...)?
dsComponents.Tables["MemoryHistory"].Rows.Clear()
should work properly. Are you sure it's hitting that line of code and nothing else is interfering with it?foreach
loop and then add/remove elements to the collection inside the loop, so you could try an old fashionedfor
loop but go backwards,for (int i = dsComponents.Tables["MemoryHistory"].Rows.Count - 1; i >= 0; i--)
and then calldsComponents.Tables["MemoryHistory"].Rows[i].Delete()
inside the loop