none
Collection was modified; enumeration operation may not execute

    Question

  • Hello,
     

    I am trying to perform a task with a hash table the problem is in the foreach loop (in tab DictionaryEntry d),
    which gives the following error "Collection was modified; enumeration operation may not execute."
    I think the problem is that the tab has been modified.
    How can I resolve this situation.

        

             

    Monday, April 06, 2009 11:12 PM

Answers

  • You cannot modify a collection (such as your HashTable) while you're enumerating it.

    When you do foreach (DictionaryEntry d in tab) {...}, you are indirectly creating an enumerator.

    During this, you cannot add a new element to the collection, or the next step through the enumerator will throw an exception.

    If you need this behavior, you should create the list of items to add, then add them at the end (after the foreach).  This will prevent this exception from occurring.
    Monday, April 06, 2009 11:25 PM

All replies

  • You cannot modify a collection (such as your HashTable) while you're enumerating it.

    When you do foreach (DictionaryEntry d in tab) {...}, you are indirectly creating an enumerator.

    During this, you cannot add a new element to the collection, or the next step through the enumerator will throw an exception.

    If you need this behavior, you should create the list of items to add, then add them at the end (after the foreach).  This will prevent this exception from occurring.
    Monday, April 06, 2009 11:25 PM
  • In order to modify a collection consider the following code :


    Public Class Employee

                  private _active as boolean
                  Public Property IsActive() As Boolean
                    Get
                                 Return _active
                    End Get
                    Set(ByVal value As Boolean)
                                 _active = value
                     End Set
        End Property
    End Class

    Now suppose we have list of employees objects loaded in a hash table htEmployee. Using this htEmployee suppose  we populate a checked listview control
    and the active employees are checked and unactive are unchecked. Now when we make check or uncheck operation on any employee we will have to modify it in the htEmployee.

    First copy this htEmployee to a temp hash table make changes there and then copy is back to htEmployee.

    It will not give the mentioned error.


    A Learner
    Saturday, July 04, 2009 8:12 PM