Removing elements in collections

Posted on 2005-05-05
Last Modified: 2010-04-16
it seems like collections like array list and hashtables dont allow removing elements inside a loop ?

Am I correct ?
Question by:deersuper
    LVL 1

    Accepted Solution

    Yes. You're correct. You get an "System.InvalidOperationException: Collection was modified; enumeration operation may not execute." exception if you try to do it.

    To get around this I make a copy of the collection and remove the items from the copy as I'm looping through the original collection.
    LVL 7

    Expert Comment

    during a foreach loop you can't do it, but you can through a standard while or for loop.
    for(int i = 0; i < ArrayList.count;i++)
      if(Delete ArraList[i])

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Suggested Solutions

    We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now