Removing item from NameValueCollection

  • Thread starter Thread starter Walter Zydhek
  • Start date Start date
W

Walter Zydhek

I am having a problem using the NameValueCollection type.

If I remove one of the items while iterating through an
collection of this type, I end up with an exception.
This exception is:
Collection was modified after the enumerator was
instantiated.

This happens when it attempts to continue through the
enumeration.

Is there a way around this? Is there another way to
remove items from the collection while iterating through
it?

-Walter Zydhek
 
Walter Zydhek said:
I am having a problem using the NameValueCollection type.

If I remove one of the items while iterating through an
collection of this type, I end up with an exception.
This exception is:
Collection was modified after the enumerator was
instantiated.

This happens when it attempts to continue through the
enumeration.

Is there a way around this? Is there another way to
remove items from the collection while iterating through
it?

Not using a straight foreach, no. The most common way of getting round
it is to create another collection for all the items to remove, and
then remove them all after the first iteration.
 
You could iterate starting at the end using a standard "for" loop
decrementing the index for each item. When you come across an item that you
do not want, you can remove it and continue. The reason for starting at the
end is because as you remove the item, the length of the collection changes
so your loop's ending condition is no longer valid. However, the index for
the first element never changes.
 
Actually, I found a better (native?) way of doing it which
makes more sense I guess.

This method is to do the for-each on a NEW instance of the
NameValueCollection passing the existing
NameValueCollection in the New Constructor. Then removing
the items from the original collection. It works great for
me.

Example:

dim a as new NameValueCollection
a.add("name-a","value-a")
a.add("name-b","value-b")
a.add("name-c","value-c")

dim item as string
for each item in New NameValueCollection(a)
if a(item) = "value-b" then
a.remove(item)
end if
next

this will result in value-b being removed, but not
interrupting the for-each loop

-Walt
 
Back
Top