InvalidOperationException after removing an elemen

2020-04-18 08:48发布

Hi I am trying to remove all numbers that are divisible by two from the arrayList.The probleme is that after one element is removed I get an InvalidOperationException.

   private ArrayList RemoveDivTwo(ArrayList list) {
        int count = 0;
        foreach(int i in list){
            if ((i > 2) && (i % 2 == 0)) {
                list.RemoveAt(count); 
            }
            count++;
        }

        return list;
    }

How can I solve this problem so I wont't get an exception and be able to remove all elements divisible by two?

标签: c#
3条回答
干净又极端
2楼-- · 2020-04-18 09:36

The exception is thrown because, foreach loop calls collectionName.GetEnumerator method before it starts iterating through the list of items. GetEnumerator is not called again unless you start a new foreach loop on the collection. The list cannot be modified inside the foreach loop, it is meant only for read-only operations on the list.

You may use for loop for iterating as well as modifying the elements from the list.

查看更多
贪生不怕死
3楼-- · 2020-04-18 09:40

Try iterating over it this way.

for(int i = 0; i < list.Count(); i++){
   if ((list[i] > 2) && (list[i] % 2 == 0)) {
                list.RemoveAt(i); 
                i--; //as offsets have shifted by one due to removal
            }
}

You are no longer iterating over the list. So this should work.

查看更多
爷、活的狠高调
4楼-- · 2020-04-18 09:40

I wouldn't even bother removing elements. Just return the elements you do want as a new list:

List<int> RemoveDivTwo(List<int> list) {
    return list.Where(i => i % 2 == 1 || i <= 2).ToList();
}
查看更多
登录 后发表回答