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

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

    Using .ToList() will make a copy of your list, as explained in this question: ToList()-- Does it Create a New List?

    By using ToList(), you can remove from your original list, because you're actually iterating over a copy.

    foreach (var item in listTracked.ToList()) {    
    
            if (DetermineIfRequiresRemoval(item)) {
                listTracked.Remove(item)
            }
    
         }
    

提交回复
热议问题