Intelligent way of removing items from a List while enumerating in C#

后端 未结 10 554
闹比i
闹比i 2020-11-29 19:05

I have the classic case of trying to remove an item from a collection while enumerating it in a loop:

List myIntCollection = new List()         


        
10条回答
  •  温柔的废话
    2020-11-29 20:07

    If you're interested in high performance, you can use two lists. The following minimises garbage collection, maximises memory locality and never actually removes an item from a list, which is very inefficient if it's not the last item.

    private void RemoveItems()
    {
        _newList.Clear();
    
        foreach (var item in _list)
        {
            item.Process();
            if (!item.NeedsRemoving())
                _newList.Add(item);
        }
    
        var swap = _list;
        _list = _newList;
        _newList = swap;
    }
    

提交回复
热议问题