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

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

    In C# one easy way is to mark the ones you wish to delete then create a new list to iterate over...

    foreach(var item in list.ToList()){if(item.Delete) list.Remove(item);}  
    

    or even simpler use linq....

    list.RemoveAll(p=>p.Delete);
    

    but it is worth considering if other tasks or threads will have access to the same list at the same time you are busy removing, and maybe use a ConcurrentList instead.

提交回复
热议问题