I wanted to remove all elements in a collection and since I didn't see .RemoveAll
or such I went with the code below.
int number = addressBook.Items.Count;
System.Collections.IEnumerator enumerator = ...
while (enumerator.MoveNext())
{
target = enumerator.Current as Outlook.ContactItem;
target.Delete();
}
However, I noticed that the number of remaining elements in the collection is roughly the half for each run of the program. My conclusion was that .Delete()
skips to the next element by itself, meaning that .MoveNext()
i nthe condition for the loop jumps to the elements after the next.
So I tried to reset the enumerator as follows.
int number = addressBook.Items.Count;
System.Collections.IEnumerator enumerator = ...
while (enumerator.MoveNext())
{
target = enumerator.Current as Outlook.ContactItem;
target.Delete();
enumerator.Reset();
}
However, as I checked the .Count
I saw that the number of elements remaining was still 1 after the last element being deleted and the enumerator being reset. And of course I got an exception thrown in my face.
What am I missing in this picture? I know it's not a bug because that would be reported and resolved eons ago...