ArrayList Remove Item

G

Guest

Hi ALL

I have create ArrayList Object, I want to loop to remove someitem in the
ArrayList.
However, it pops me exception.

The example is

foreach(string s in arraylist){
if(s.Equals("test"))
arraylist.Remove(s);
}
when it removes one item and do the next loop, it will pops me up an
exception:

"Collection was modified; enumeration operation may not execute."

I have googled, and the solution is from last to the first?
Does it sound silly?

Thanks
 
G

Guest

When you remove an item, the item indexer becomes invalid becasue everything
shifts. Iterate backward by index.
 
N

Norman Rericha

you could also change your code to, in order to eliminate a direct
dependence on indexes in your arraylist.

while(ArrayList.Contains("test"))
{
ArrayList.RemoveAt(ArrayList.IndexOf("test"));
}

or

int _index = ArrayList.IndexOf("test");
while(_index >= 0)
{
Arraylist.RemoveAt(_index);
_index = ArrayList.IndexOf("test");
}
 

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

Top