且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为了避免出现InvalidOperationException***实践:集合已修改?

更新时间:2023-01-22 17:23:52

这是直接烤成名单,其中,T>

  lines.RemoveAll(行=> line.FullfilsCertainConditions());
 

或C#2.0:

  lines.RemoveAll(委托(行线){
    返回line.FullfilsCertainConditions();
});
 


在非 - 名单,其中,T> 情况下(你编辑的问题),你可以换这个类似下面(未经测试):

 静态类CollectionUtils
{
    公共静态无效removeall过< T>(IList的< T>清单,predicate< T> predicate)
    {
        诠释计数= list.Count;
        而(count--大于0)
        {
            如果(predicate(名单[计数]))list.RemoveAt(计数);
        }
    }
    公共静态无效removeall过(IList的列表,predicate<对象> predicate)
    {
        诠释计数= list.Count;
        而(count--大于0)
        {
            如果(predicate(名单[计数]))list.RemoveAt(计数);
        }
    }
}
 

由于 UIElementCollection 实现(非通用)的IList 这应该工作。而且比较方便,用C#3.0,你可以添加一个的IList / 的IList< T&GT ; ,并把它作为一个扩展的方法。唯一需要说明的是,该参数的匿名法将对象,所以你需要转换它扔掉。

Very often I need something like that:

 foreach (Line line in lines)
 {
    if (line.FullfilsCertainConditions())
    {
       lines.Remove(line)
    }
 }

This does not work, because I always get a InvalidOperationException because the Enumerator was changed during the loop.

So I changed all my loops of this kind to the following:

List<Line> remove = new List<Line>();
foreach (Line line in lines)
{
   if (line.FullfilsCertainConditions())
   {
      remove.Add(line)
   }
}

foreach (Line line in remove) {
{
   lines.Remove(line);
}

I'm not sure if this is really the best way since in the worst case I have to iterate 2 times over the original list and so it needs time 2n instead of n.

Is there a better way to do this?

EDIT:

I was able to do that using Mark's answer!But what if my collection doesn't implements RemoveAll()?

For example a

System.Windows.Controls.UIElementCollection

EDIT 2:

Again with the help of Mark I'm now able to make the following call to remove all ScatterViewItems:

CollectionUtils.RemoveAll(manager.getWindow().IconDisplay.Items, elem => elem.GetType() == typeof(ScatterViewItem));

This is baked directly into List<T>:

lines.RemoveAll(line => line.FullfilsCertainConditions());

or in C# 2.0:

lines.RemoveAll(delegate(Line line) {
    return line.FullfilsCertainConditions();
});


In the non-List<T> case (your edit to the question), you could wrap this something like below (untested):

static class CollectionUtils
{
    public static void RemoveAll<T>(IList<T> list, Predicate<T> predicate)
    {
        int count = list.Count;
        while (count-- > 0)
        {
            if (predicate(list[count])) list.RemoveAt(count);
        }
    }
    public static void RemoveAll(IList list, Predicate<object> predicate)
    {
        int count = list.Count;
        while (count-- > 0)
        {
            if (predicate(list[count])) list.RemoveAt(count);
        }
    }
}

Since UIElementCollection implements the (non-generic) IList this should work. And quite conveniently, with C# 3.0 you can add a this before IList / IList<T> and have it as an extension method. The only subtlety is that the parameter to the anon-method will be object, so you'll need to cast it away.