1

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?

3
  • This is a common one. Remember that you can't add/remove items to/from a collection if you're iterating with a foreach. Commented Oct 20, 2012 at 11:26
  • If you are thinking,why is this an invalid op,Please read this stackoverflow.com/questions/1124221/… Commented Oct 20, 2012 at 11:32
  • ArrayList is not a preferred collection type, unless you are working with legacy 1.1 code. Use a List<int> instead. Using a List<int> your code could be rewritten to list.RemoveAll(i => i > 2 && i % 2 == 0) Commented Oct 20, 2012 at 11:53

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the only problem with this is that I am using an arrayList and I can not get the elements threw indexes
Yes you can; you'll just have to cast them back to int. This is another reason to use List<int> if you possibly can.
1

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.

Comments

1

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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.