« How to add your own template on Visual Studio .NET | Main | Piracy is Good »

June 18, 2005

DataRow deletion

Often you need to loop through the rows in a DataTable, pick up the invalid ones and delete them. This can be tciky because the Rows property in a DataTable is a collection and Delete() method actually removes the row from the collection, and this isn't good when you’re enumerating in a collection.


foreach (DataRow row in dataTable.Rows)
{
if (row.Id < 0)
row.Delete(); // Whoops not good, deleting the content of collection while enumerating it
}

This way also will cause problem:


for (int i = 0; i < dataTable.Rows.Count; i++)
{
if (dataTable.Rows[i].Id < 0)
dataTable.Rows[i].Delete();
}


This is because as soon as you call delete dataTable.Rows.Count will go down 1 as well since Rows is a collection. So how to do this? Well you can add all the rows that you want to delete into an ArrayList and delete it from there, but there's a better and more elegant solution for this problem. The key is the Select() method in the DataTable. The Select() method is very powerful and you can do pretty much almost any SQL constraints here and even some basic functions such as Trim().


DataRow[] rows = dataTable.Select("Id < 0");
foreach (DataRow row in rows)
{
row.Delete();
}

Posted by vhadiant at June 18, 2005 12:13 PM





Comments

But my question is then the performance hit. I'm assuming the "select" filter is re-evaluated every time?

Posted by: Minh at June 20, 2005 02:00 PM

It should be fine. Select() is only evaluated once and once only when you do dataTable.Select(). The result is copied into an array and you loop through that array.

Posted by: Victor Hadianto [TypeKey Profile Page] at June 20, 2005 04:00 PM

Post a comment





Remember Me?

(you may use HTML tags for style)