How to remove item from ObservableCollection? [duplicate]
-
24-06-2021 - |
Question
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();
}
}
OTHER TIPS
Two ways you could approach this:
- If you don't need to remove everything from the list, use your
foreach
to populate a separate list of "items to be closed," and call.Close
for each item in the second list when you're done. That way, you avoid modifyingmycollection
while you enumerate. If you're calling
Close
on every item in the list, try this instead:while (mycollection.Count > 0 { mycollection[0].Close()) }
In the foreach, use mycollection.ToList()
instead.