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

前端 未结 27 2313
忘了有多久
忘了有多久 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:21

    Trace the elements to be removed with a property, and remove them all after process.

    using System.Linq;
    
    List _Group = new List();
    // ... add elements
    
    bool cond = true;
    foreach (MyProperty currObj in _Group)
    {
        if (cond) 
        {
            // SET - element can be deleted
            currObj.REMOVE_ME = true;
        }
    }
    // RESET
    _Group.RemoveAll(r => r.REMOVE_ME);
    

提交回复
热议问题