如何从ObservableCollection中删除项目?

Ken*_*hou 3 c# ienumerable foreach observablecollection enumerator

可能重复:
修改foreach中列表的最佳方法是什么?

假设我有一个ObservableCollection mycollection,我想通过枚举器做一些事情:

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

该方法Close()有一行代码 - mycollection.Remove(x);.当我运行此代码时,得到以下错误:

收集被修改; 枚举操作可能无法执行.

我无法更改方法,Close()因为它在应用程序的许多其他地方被调用.我该如何解决这个问题?

Adi*_*ter 7

枚举集合时无法删除项目.一个简单的解决方案是使用for从最后一项到第一项的循环并根据需要删除:

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