Thursday, July 21, 2005

Where art thou Java iterators?

So the C# equivalent to the Java iterator is the "Enumerator" class. As much as I like the foreach block and simple iteration in C#, I miss the ability to delete items from my collections while I traverse them like I can do in Java.

MSDN has an article (and slight fix/kludge) about this,

When this code is run, it generates an exception because you can't modify a collection while you're enumerating over it. That's a pretty good idea since you usually don't want collections to change underneath you, but it's sometimes annoying.

This got me thinking, and I realized that what was needed was a class that would isolate the enumeration from the collection. This class would do a full enumeration over the collection and store the data away to expose its own enumerable object. Changing the collection while using that object would be okay.

No comments: