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?
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.
Try iterating over it this way.
You are no longer iterating over the list. So this should work.
I wouldn't even bother removing elements. Just return the elements you do want as a new list: