-2

An exception gets thrown because the ClientStack.Children range changes after a ClientStack.Children member (textblock) gets removed:

foreach (TextBlock textblock in ClientStack.Children)
{
    if ((string)textblock.ToolTip == e.IP)
    {
        ClientStack.Children.Remove(textblock);
        // update foreach loop's range???
    }
}

Is there a way to update this foreach loop's range after a ClientStack.Children member gets removed?

Tino Hager
  • 698
  • 5
  • 18
demented
  • 1
  • 4

2 Answers2

1

You cannot modify a collection while you are enumerating it, so you get that exception.

You could use a backwards for-loop:

for(int i = ClientStack.Children.Count - 1; i >= 0; i--)
{
    if (((string)ClientStack.Children[i]).ToolTip == e.IP)
    {
        ClientStack.Children.RemoveAt(i);
    }
}

Another - little bit less efficient - way was to use a remove-collection:

var removeBlocks = ClientStack.Children.Cast<object>()
    .Where(textblock => ((string)textblock).ToolTip == e.IP)
    .ToList();
removeBlocks.ForEach(ClientStack.Children.Remove); 
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
0

There is no way to update the range while iterating. Instead make a copy of the collection and iterate over that, but remove from the original collection.

foreach (TextBlock textblock in ClientStack.Children.ToList())
{
    if ((string)textblock.ToolTip == e.IP)
    {
        ClientStack.Children.Remove(textblock);
    }
}
Kit
  • 17,129
  • 4
  • 56
  • 95