English 中文(简体)
收集工作经过修改;在ArrayList [复制]不得进行统计工作。
原标题:Collection was modified; enumeration operation may not execute in ArrayList [duplicate]

I m trying to remove an item from an ArrayList and I get this Exception:
Collection was modified; enumeration operation may not execute.

任何想法?

最佳回答

您是在<条码>上删除该项目的。 简言之,你可以 t。 这里有一些共同选择:

  • use List<T> and RemoveAll with a predicate
  • 按指数分类的后向,去除对应物品

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • <foreach,并将对应项目列入第二个清单;现在列出第二个清单,并从第一个清单中删除这些项目(如果你看到我指的是什么)。

问题回答

这里的一个例子是(任何类型)

var itemsToRemove = new ArrayList();  // should use generic List if you can

foreach (var item in originalArrayList) {
  if (...) {
    itemsToRemove.Add(item);
  }
}

foreach (var item in itemsToRemove) {
  originalArrayList.Remove(item);
}

OR 如果你重新使用3.5,Linq使第一种轨道更容易:

itemsToRemove = originalArrayList
  .Where(item => ...)
  .ToArray();

foreach (var item in itemsToRemove) {
  originalArrayList.Remove(item);
}

将“......”改为“......”。

一种办法是在新的清单中增加拟删除的项目。 然后处理和删除这些项目。

我愿通过<<><>t>>for loop>,但与foreach相比,这可以ious。 我所希望的一种解决办法是建立一个统计员,使名单落后。 您可在<代码>ArrayList或List<T>上实施这一推广方法。 <代码>ArrayList的实施如下。

    public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

<代码>List<T>的实施类似。

    public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

下面的例子利用统计员从中删除所有甚至分类账。

    ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    foreach (int item in list.GetRemoveSafeEnumerator())
    {
        if (item % 2 == 0)
            list.Remove(item);
    }

承诺修改名单。

相反,使用“<>代码>(>或>(<>>/code>,附索引后。 (这将允许你在不产生一个无效指数的情况下删除物品。)

var foo = new List<Bar>();

for(int i = foo.Count-1; i >= 0; --i)
{
  var item = foo[i];
  // do something with item
}

我失踪了吗? 有些人对我说错了。

list.RemoveAll(s => s.Name == "Fred");

采用一种(a)的样子,而不是数字指数。

我同意我在此职位上宣读的几点意见,我将其纳入我的解决办法,解决与原职位同样的问题。

尽管如此,我赞赏以下评论:

  • “除非您使用1.0或1.1,使用List<T>而不是ArrayList

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.

e.g.

private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] {  ;  }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID s and cleanup the string holding the list if ID s
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

...
public List<string> ParseList(List<string> checkList)
{
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
        verifiedList.Add(listItem.Trim());

    verifiedList.Sort();
    return verifiedList;
}        

使用<代码>ArrayList 你们也可以这样做。

ArrayList arraylist = ... // myobject data list

ArrayList temp = (ArrayList)arraylist.Clone();

foreach (var item in temp)
{
      if (...)
         arraylist.Remove(item);
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签