Results 1 to 3 of 3

Thread: Problem removing object from collection (RESOLVED)

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2002
    Location
    London
    Posts
    63

    Problem removing object from collection (RESOLVED)

    I have a SortedList called m_FieldMappings.

    All objects in it that are marked 'Delete', i want to remove from the SortedList.

    foreach (FieldMapping map in m_FieldMappings.GetValueList())
    {
    if (map.DBState == enDBAction.Delete) m_FieldMappings.Remove(map.key);
    }

    The problem seems to be that since I am doing a foreach, the collection should not change otherwise you get an enumeration error.

    I'm looking for another way of doing this.
    Last edited by Genie; Aug 18th, 2003 at 06:57 AM.

  2. #2
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Use the enumerator directly. Use two enumerators, one to point to the value that gets deleted, another to point at the next value to continue enumeration.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2002
    Location
    London
    Posts
    63

    Smile

    Thats great CornedBee. Heres' what I wrote and works great.

    Seems a good general solution.


    IDictionaryEnumerator en = m_FieldMappings.GetEnumerator();
    en.Reset();

    if (en.MoveNext())
    {
    while (true)
    {
    //en.Current; -- don't need since en.Value points to current object
    FieldMapping map = (FieldMapping) en.Value;
    if (map.DBState == enDBAction.Delete)
    {
    m_FieldMappings.Remove(map.key);
    // re-create the enumerator, since it will have been invalidated.
    en = m_FieldMappings.GetEnumerator();
    en.Reset();
    }

    if (!en.MoveNext())
    {
    break;
    }
    }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width