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

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

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

    Simply create an entirely new list from the first one. I say "Easy" rather than "Right" as creating an entirely new list probably comes at a performance premium over the previous method (I haven't bothered with any benchmarking.) I generally prefer this pattern, it can also be useful in overcoming Linq-To-Entities limitations.

    for(i = list.Count()-1;i>=0;i--)
    
    {
    
    item=list[i];
    
    if (item.Delete) list.Remove(item);
    
    }
    

    This way cycles through the list backwards with a plain old For loop. Doing this forwards could be problematic if the size of the collection changes, but backwards should always be safe.

提交回复
热议问题