using IEnumerator to removing items

I want to remove some items from an ArrayList. Can I do that using a foreach(…)- loop an IEnumerator like this.

foreach(string s in arraylist)

{

if (s == “del”)

{

// Here I want to remove the item from arraylist…

}

}

Any ideas how to solve this without creating a new ArrayList and add items I want to save. Feels like that solution will bee to time consuming…

All tips are welcomed!.




Answer this question

using IEnumerator to removing items

  • Pete0511

    You can't do this with an enumerator because when you change the collection while enumerating an exception is thrown.

    To solve this problem use a for-loop, or a while with index of. Here are the two examples:

    For-loop

    for( int i = 0; i < arraylist.Count; i++ )
    {
        string currentValue = (string)arraylist[ i ];
       
        if( currentValue.Equals( "del" ) )
        {
            // TODO: Do delete logic here.
           
            // Lower the current index value
            // because a other value  will be
            // available on that index.
            i--;
        }
    }

     


    While-loop

    int index = 0;

    while( (index = arraylist.IndexOf( "del" )) != -1 )
    {
        arraylist.RemoteAt( index );
    }

     



  • wirol

    Indeed, you can't use a foreach to delete items in a collection, since the collection will change.
    However, this for-loop that P.J. Van de Sande posts can be written better like this:



    for( int i = arrayList.Count - 1; i >= 0; i -- )
    {
       if( arrayList[ i ].ToString == "del" )
       {
             arrayList.RemoveAt( i );
       }
    }

     


  • Seraph Jiang

    Indeed, good notice Frederik! Now when you remove at item at the index it won't effect the other items because you remove the item from the end.

  • using IEnumerator to removing items