我怎么能做这个特殊的foreach迭代器?

ala*_*a27 0 .net c#

可能重复:
如何在C#中迭代可枚举集合中的项目时修改或删除项目

听着,我不想知道基本的foreach.我在谈论控制这个错误的那个:

"The enumerator is not valid because the collection changed."

当我这样做时会发生这种情况:

foreach(Image image in images)
{
   if(...)
   {
       images.remove(image)
   }
}
Run Code Online (Sandbox Code Playgroud)

我相信有一个特殊的迭代器可以很好地处理这个问题,就像Java一样.那么,我怎么能在C#中做到这一点呢?谢谢!

Cod*_*aos 5

或者只是删除它而不需要手动迭代:

images.RemoveAll(image=>...)
Run Code Online (Sandbox Code Playgroud)

适用List<T>但很多其他容器不支持它.

一个O(n)解决方案IList<T>:

void RemoveWhere(this IList<T> list,Predicate<T> pred)
{
    int targetIndex=0;
    for(int srcIndex=0;srcIndex<list.Count;srcIndex++)
    {
      if(pred(list[srcIndex]))
      {
        list[targetIndex]=list[srcIndex];
        targetIndex++;
      }
      for(int i=list.Count-1;i>=targetIndex;i--)
        list.RemoveAt(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

在你点击第一个被删除的项目之前,可以通过不分配加快一点.