Search code examples
c#foreachienumerableobservablecollectionenumerator

How to remove item from ObservableCollection?


Possible Duplicate:
What is the best way to modify a list in a foreach?

Suppose I have an ObservableCollection mycollection and I want to do something by enumerator like:

foreach(var x in mycollection)
{
   // This will do something based on data of x and remove x from mycollection
   x.Close();
}

The method Close() has one line of code - mycollection.Remove(x);. When I run this code, get the following error:

Collection was modified; enumeration operation may not execute.

I can't change method Close() because it is called in a lot of other places in the application. How can I resolve this issue?


Solution

  • You can't remove items while enumerating the collection. One simple solution is to use a for loop going from the last item to the first and remove as necessary:

    for (int i = myCollection.Count - 1; i >= 0; i--)
    {
        var item = myCollection[i];
        if (ShouldDelete(item))
        {
            item.Close();
        }
    }