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

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

    If the function that determines which items to delete has no side effects and doesn't mutate the item (it's a pure function), a simple and efficient (linear time) solution is:

    list.RemoveAll(condition);
    

    If there are side effects, I'd use something like:

    var toRemove = new HashSet();
    foreach(var item in items)
    {
         ...
         if(condition)
              toRemove.Add(item);
    }
    items.RemoveAll(toRemove.Contains);
    

    This is still linear time, assuming the hash is good. But it has an increased memory use due to the hashset.

    Finally if your list is only an IList instead of a List I suggest my answer to How can I do this special foreach iterator?. This will have linear runtime given typical implementations of IList, compared with quadratic runtime of many other answers.

提交回复
热议问题