How to remove specific object in ArrayLisit()?

my code is,

var statmods = new ArrayList(); 
 
class MODEntry{  
 var who : int;    // affect to who?
 var name : String = "";  // what stat? 
 var sum : int;   // how much?
 var turn : int;    // how long?  
 var type : String;
 var on : boolean = true;    // if this is false, remove this effect immediately.
}
function Reset(){
for (var mod : MODEntry in statmods){
  mod.turn--;
  if(mod.turn == -1)
   statmods.Remove(mod);
 }
}

Why this result errors like below?

InvalidOperationException: List has changed.
System.Collections.ArrayList+SimpleEnumerator.MoveNext ()

And I met ourofrange error too when I change that for syntax to for(x = 0 ; x<statmods.Count ; x++), and statmods.RemoveAt[×];

Then how to remove object in MODEntry class if it’s [turn] variables become -1?

Thanks.

Hi,

did you try to remove them after the loop ? Or is this something you want to avoid ?

I just had a thought, if you remove the current element, your iterator can’t go to the next one. That’s probably the reason why you have those out of range errors but that’s just a thought, I may be wrong

Do you really need to use an array list ? Maybe you could use a linked list instead ?

Add elements that need to be removed to a new list then after the for loop do remove them with statmods.RemoveRange(newList);

Thank you link! I think link to different website is ok, cuz it is useful. It may works well, I will test.
Why use ArrayList? I don’t know why. Just all I know is Array and ArrayList.
Any other more good option alternative?

Thanks.
But how about this.

http://bytes.com/topic/c-sharp/answers/699414-remove-arraylist-n-inside-foreach-loop

You could do it with an ArrayList for sure, just try on of those solution on the link you posted, am sure they will do the job well ; )
Scarpelius was right, it’s a way to do it, but creating another list to remove into your current list is not the way I’d do it, but for sure it would works !

One idea I’d give a try if i were you was going backward through the list (dunno if I’m clear).

for (int index = myArrayList.Count - 1; index >= 0; index--)
{
// Get the item.
myEntry entry = (myEntry) myArrayList[index];

// Check to remove.
if (entry.fieldA == 0)
{
// Remove.
myArrayList.RemoveAt(index);
}
}

Otherwise you could give a look at the linked list if you are interested :

In general modifying a collection that you are currently iterating over is a very very bad idea.