Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modify Collection during enumeration

Status
Not open for further replies.

dragonwell

Programmer
Oct 21, 2002
863
US
I found out that this won't work:

Code:
foreach(MyType myType in myTypeCollection){

    myTypeCollection.Remove(myType)
}

I need to iterate over an ArrayList and remove an object if it meets a criteria but I get "Collection was modified; enumeration operation may not execute."

What is the alternate code?

Thanks,

David
[pipe]
 
Got it.
Code:
MyTypeCollection newCollection = new MyTypeCollection();

//add any good ones from the old into the new
foreach(MyType myType in original_myTypeCollection)
{
    if(myType.Criteria)
    newCollection.Add(myType);
}

//clear out the old and add all the new to it
original_myTypeCollection.Clear();
original_myTypeCollection.AddRange(newCollection);
 
There's a blurb in the docs saying that enumerating through a collection is not thread-safe. Which means that anything that changes the contents of the collection while you're enumerating it then makes the enumerator invalid (you must start over from the beginning).

CHip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top