delete loop

G

G. Dean Blake

When I do this.....

myDA.SelectCommand.Parameters("@SCID").Value = scid
Dim dt As New DataTable
myDA.Fill(dt)
If dt.Rows.Count > 0 Then
Dim myRow As DataRow = dt.Rows(0)
For Each myRow In dt.Rows
dt.Rows.Remove(myRow)
Next
End If

I get this exception....

Collection was modified; enumeration operation may not execute.


Why?
Thanks,
Dean
 
S

Scott Allen

Hi Dean:

The foreach statement uses an Enumerator, which is a little object
optimized to move through a collection which doesn't change. The
enumerator carries a little bit of "state" about the collection it is
moving through. If the collection changes the state is invalid and the
enumerator doesn't know what the "right thing to do" is - it's pretty
dumb :)

Think of it as a way to avoid subtle problems like this:

string[] names = { "Tim", "Tim", "Gil" };
ArrayList nameList = new ArrayList( names );

for(int i = 0; i < nameList.Count; i++)
{
if((string)nameList == "Tim")
{
nameList.Remove(nameList);
}
}

The code above intends to remove all the "Tim" strings from the
collection but it doesn't. It will skip right over the second "Tim"
entry because the collection was modified and the state (i) could not
account for it.

One way I could write this to work would be like:

for(int i = nameList.Count - 1; i >= 0; i--)
{
if((string)nameList == "Tim")
{
nameList.Remove(nameList);
}
}

HTH,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top