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

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

    Copy the list you are iterating. Then remove from the copy and interate the original. Going backwards is confusing and doesn't work well when looping in parallel.

    var ids = new List { 1, 2, 3, 4 };
    var iterableIds = ids.ToList();
    
    Parallel.ForEach(iterableIds, id =>
    {
        ids.Remove(id);
    });
    

提交回复
热议问题