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

后端 未结 10 603
闹比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 19:59

    When you need to iterate through a list and might modify it during the loop then you are better off using a for loop:

    for (int i = 0; i < myIntCollection.Count; i++)
    {
        if (myIntCollection[i] == 42)
        {
            myIntCollection.Remove(i);
            i--;
        }
    }
    

    Of course you must be careful, for example I decrement i whenever an item is removed as otherwise we will skip entries (an alternative is to go backwards though the list).

    If you have Linq then you should just use RemoveAll as dlev has suggested.

提交回复
热议问题