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

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

    Let's add you code:

    List myIntCollection=new List();
    myIntCollection.Add(42);
    myIntCollection.Add(12);
    myIntCollection.Add(96);
    myIntCollection.Add(25);
    

    If you want to change the list while you're in a foreach, you must type .ToList()

    foreach(int i in myIntCollection.ToList())
    {
        if (i == 42)
           myIntCollection.Remove(96);
        if (i == 25)
           myIntCollection.Remove(42);
    }
    

提交回复
热议问题