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

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

    I know this post is old, but I thought I'd share what worked for me.

    Create a copy of the list for enumerating, and then in the for each loop, you can process on the copied values, and remove/add/whatever with the source list.

    private void ProcessAndRemove(IList list)
    {
        foreach (var item in list.ToList())
        {
            if (item.DeterminingFactor > 10)
            {
                list.Remove(item);
            }
        }
    }
    

提交回复
热议问题