Delete elements in .NET collections

  • Thread starter Thread starter headware
  • Start date Start date
H

headware

A common issue that I see in the
microsoft.public.dotnet.framework.adonet group is that if you want to
delete a DataRow from a collection of DataRows (e.g. myTable.Rows), you
can't do this using a foreach loop like this:

foreach(DataRow row in myTbl.Rows)
if(someCondition)
row.Delete();

You must instead use a regular for loop and loop from back to front
like this:

for(int i = myTbl.Rows.Count - 1; i >= 0; i--)
if(someCondition)
myTbl.Rows.Delete();

I understand why you must do this. My question is whether this is a
standard situation in .NET collection classes.

I have an XML file that I'm processing using the DOM classes
(XmlDocument, XmlNode, etc.) and I need to loop through the children of
an XmlNode and call a function on each one that may or may not delete
that child. Of course, if I use a foreach loop or a for loop that loops
from front to back, the loop counter gets messed up when I delete a
node. It seems to work when I use the same solution as listed above
with the DataRows, but I wanted to confirm that it was a valid solution
in this case.

I can't find any Microsoft documentation regarding this so I was hoping
somebody would be able to point me to some or maybe there would be
somebody with some "inside" knowledge about this issue.

Thanks,
Dave
 
headware said:
A common issue that I see in the
microsoft.public.dotnet.framework.adonet group is that if you want to
delete a DataRow from a collection of DataRows (e.g. myTable.Rows), you
can't do this using a foreach loop like this:

foreach(DataRow row in myTbl.Rows)
if(someCondition)
row.Delete();

You must instead use a regular for loop and loop from back to front
like this:

for(int i = myTbl.Rows.Count - 1; i >= 0; i--)
if(someCondition)
myTbl.Rows.Delete();


This can be marvellously inefficient if the row set is large and more
than a few rows are to be deleted: the runtime is most likely
quadratic.

Peter
 
Of course, if Micorsoft changes the code so that when an item is
deleted from the list, it fills in the empty space from front to back
instead of back to front, that's going to break lots of code.
 
Back
Top