How to remove elements from a generic list while iterating over it?

前端 未结 27 2326
忘了有多久
忘了有多久 2020-11-21 22:48

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from

27条回答
  •  情深已故
    2020-11-21 23:31

    I wish the "pattern" was something like this:

    foreach( thing in thingpile )
    {
        if( /* condition#1 */ )
        {
            foreach.markfordeleting( thing );
        }
        elseif( /* condition#2 */ )
        {
            foreach.markforkeeping( thing );
        }
    } 
    foreachcompleted
    {
        // then the programmer's choices would be:
    
        // delete everything that was marked for deleting
        foreach.deletenow(thingpile); 
    
        // ...or... keep only things that were marked for keeping
        foreach.keepnow(thingpile);
    
        // ...or even... make a new list of the unmarked items
        others = foreach.unmarked(thingpile);   
    }
    

    This would align the code with the process that goes on in the programmer's brain.

提交回复
热议问题