"removing items within a foreach isn't reliable" - BrokenRulesCollection.Remove() ?

"removing items within a foreach isn't reliable" - BrokenRulesCollection.Remove() ?

Old forum URL: forums.lhotka.net/forums/t/497.aspx


antoan posted on Wednesday, June 28, 2006

The implementation of BrokenRulesCollection makes use of a numerical counter loop instead of foreach (page 134 of 2005 book) The reason given for this in the method comments iis that "removing items within a foreach isn't reliable".


I trying to understand why?

Brian Criswell replied on Wednesday, June 28, 2006

Because foreach gets an enumerator for the IList you are enumerating over.  If you remove an item from the list, you invalidate the enumerator.

skagen00 replied on Wednesday, June 28, 2006

When using foreach, it's a general rule that you're not supposed to modify the collection by removing items within the loop. In this loop, he's removing an item, hence the for loop.

I tried to find a relevant post somewhere but I couldn't find one for you.

 

 

antoan replied on Wednesday, June 28, 2006

skagen00 , Brian,

Thanks guys, it makes sense now.

A

HarvDotNet replied on Wednesday, June 28, 2006

Use a counter and go from last to first of the collection

For int Counter = Collection.Count() - 1 to 0 Step -1

   ' Delete selected items

Next

Harvey Sather

Copyright (c) Marimer LLC