Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to implement a IEnumerator which support remove items in foreach

Discussion in 'Scripting' started by chansey97, Jul 3, 2014.

  1. chansey97

    chansey97

    Joined:
    Sep 21, 2012
    Posts:
    59
    I write some code like this:

    Code (CSharp):
    1.         var list = new List<Int32>();
    2.      
    3.         for(Int32 i=0; i<10; i++)
    4.             list.Add(i);
    5.  
    6.         IEnumerator it = list.GetEnumerator();
    7.         while (it.MoveNext())     //<---------------Exception occured:
    8.         {
    9.             var item = (Int32)it.Current;
    10.          
    11.             if (item==2)
    12.                 list.Remove(item);
    13.          
    14.             if (item==4)
    15.                 list.Remove(item);
    16.          
    17.             if (item==6)
    18.                 list.Remove(8);
    19.         }
    20.  
    21.         foreach(var item in list)
    22.             Debug.Log(item);


    Exception occured:
    Collection was modified; enumeration operation may not execute.

    My question is:
    Is it possible to rewrite IEnumerator to implement add/remove item when traversal list safely?
    Because

    Thanks.
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    not that i'm aware of. when you modify the enumeration it gets invalid and i think its a security "feature" to prevent further acess. what you can do is to store the items to remove in a separate collection (list) and after you finished enumeration iterate over this list and remove each element from the original collection. or you use linq to create an entirely new collection after your desire and "overwrite" the initial collection with it.
     
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Or use a for loop that goes backwards from the end of the collection to the beginning.
     
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,716
    Code (csharp):
    1. for (int i = collection.Count - 1; i >= 0; i++)
    2.     collection.RemoveAt(i);
    An enumator simply cannot be used if you modify the collection in any way.
     
  5. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    i guess you mean i-- ;).
     
  6. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Code (csharp):
    1.  
    2. list = list.Where(t => t != 2 && t != 4 && t != 6).ToList();
    3.