How to get around the "collection has changed" BS in C#?

Page 2 - Seeking answers? Join the AnandTech community: where nearly half-a-million members share solutions and discuss the latest tech.

Schmide

Diamond Member
Mar 7, 2002
5,694
936
126
Just off the top of my head, could you do something like this?
Code:
int i = 0;
while(i < list.length)
{
  if(list.wannaRemove(i))
  {
    list.remove(i);
  }
  else
    i++;
}

I'm no expert on C#, but I'd think it'd recalculate length when it goes back to the top of the while loop.

This is a case where you will get better performance and for that matter easier code by doing a reverse iteration over the list.

Code:
int i = list.length-1;
while(i >=0 )
{
  if(list.wannaRemove(i))
  {
    list.remove(i);
  }
  i--;
}

The reason being, depending on the management code, you will have less data to move in the large moves towards at beginning of the list as the higher items have already been removed.