ArrayList Remove Item

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
When you remove an item, the item indexer becomes invalid becasue everything
shifts. Iterate backward by index.
 
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");
}
 
Back
Top