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

后端 未结 10 574
闹比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:08

    The best solution is usually to use the RemoveAll() method:

    myList.RemoveAll(x => x.SomeProp == "SomeValue");
    

    Or, if you need certain elements removed:

    MyListType[] elems = new[] { elem1, elem2 };
    myList.RemoveAll(x => elems.Contains(x));
    

    This assume that your loop is solely intended for removal purposes, of course. If you do need to additional processing, then the best method is usually to use a for or while loop, since then you're not using an enumerator:

    for (int i = myList.Count - 1; i >= 0; i--)
    {
        // Do processing here, then...
        if (shouldRemoveCondition)
        {
            myList.RemoveAt(i);
        }
    }
    

    Going backwards ensures that you don't skip any elements.

    Response to Edit:

    If you're going to have seemingly arbitrary elements removed, the easiest method might be to just keep track of the elements you want to remove, and then remove them all at once after. Something like this:

    List toRemove = new List();
    foreach (var elem in myList)
    {
        // Do some stuff
    
        // Check for removal
        if (needToRemoveAnElement)
        {
            toRemove.Add(elem);
        }
    }
    
    // Remove everything here
    myList.RemoveAll(x => toRemove.Contains(x));
    

提交回复
热议问题