Don't Delete An Element From a Collection In foreach Loop

I faced following wierd error message while tried to manipulate a collection of WPF controls.

The enumerator is not valid because the collection changed.

My code was as following

foreach (UIElement el in aCanvas.Children)
  if (el is MyControl && (el as MyControl).data == param)
    aCanvas.Children.Remove(el);

Pretty straightforward, huh!
It was compiled okay but caused runtime error as above.
So, how to satisfy Bill in this case?
Simply do the reverse(decremental) iteration.
Following is fixed codes

UIElement el=null;
for (int inx=aCanvas.Children.Count-1; inx>=0; inx--)
  if ((el=aCanvas.Children[inx]) is MyControl
       && (el as Mycontrol).data==param)
    aCanvas.Children.Remove(el);

Now, everything works as charm.
The thing is the way of getting enumerator when they implemented Collection.
Don't delete an element during enumaration!

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License