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

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

    Just wanted to add my 2 cents to this in case this helps anyone, I had a similar problem but needed to remove multiple elements from an array list while it was being iterated over. the highest upvoted answer did it for me for the most part until I ran into errors and realized that the index was greater than the size of the array list in some instances because multiple elements were being removed but the index of the loop didn't keep track of that. I fixed this with a simple check:

    ArrayList place_holder = new ArrayList();
    place_holder.Add("1");
    place_holder.Add("2");
    place_holder.Add("3");
    place_holder.Add("4");
    
    for(int i = place_holder.Count-1; i>= 0; i--){
        if(i>= place_holder.Count){
            i = place_holder.Count-1; 
        }
    
    // some method that removes multiple elements here
    }
    

提交回复
热议问题