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?

Nistor Alexandru
  • 5,309
  • 9
  • 46
  • 71
  • This is a common one. Remember that you can't add/remove items to/from a collection if you're iterating with a `foreach`. – s.m. Oct 20 '12 at 11:26
  • If you are thinking,why is this an invalid op,Please read this http://stackoverflow.com/questions/1124221/modifying-collection-when-using-a-foreach-loop-in-c-sharp – Prabhu Murthy Oct 20 '12 at 11:32
  • `ArrayList` is not a preferred collection type, unless you are working with legacy 1.1 code. Use a [`List`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) instead. Using a `List` your code could be rewritten to `list.RemoveAll(i => i > 2 && i % 2 == 0)` – Paolo Moretti Oct 20 '12 at 11:53

3 Answers3

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.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
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.

S. Ravi Kiran
  • 4,053
  • 3
  • 21
  • 26
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();
}
Quick Joe Smith
  • 8,074
  • 3
  • 29
  • 33