C# preventing Collection Was Modified exception

前端 未结 10 1752
梦毁少年i
梦毁少年i 2021-01-17 17:16

Does

 foreach(T value in new List(oldList) )

is dangerous (costly) when oldList contains 1 millions of object T ?

More g

相关标签:
10条回答
  • 2021-01-17 17:57

    foreach(T value in new List(oldList).ToList() ) - give a try

    0 讨论(0)
  • 2021-01-17 17:58

    I usually just create a list for all the objects to be removed or added.

    Within the foreach I just add the items to the appropriate collections and modify the original collection after the foreach have completed (loop through the removeItems and addItems collection)

    0 讨论(0)
  • 2021-01-17 17:58

    You could iterate through the list without using an enumerator, so do something like...

    for(int i = 0;i<oldList.Count;i++) {
       var value = oldList[i];
    
       ...
    
       if(itemRemoveCondition) {
         oldList.RemoveAt(i--);
       }
    }
    
    0 讨论(0)
  • 2021-01-17 18:02

    just like this

    var itemsToBeRemoved = new List<T>();
    
    foreach (T item in myHugeList) 
    {
        if (/*<condition>*/)
             itemsToBeRemoved.Add(item);
    }
    
    myHugeList.RemoveRange(itemsToBeRemoved);
    
    0 讨论(0)
  • 2021-01-17 18:02

    For me, first thing is you should consider using some kind of data paging, because having such 1-milion-items-large list could be dangerous itself.

    Have you heard about Unit of Work pattern?

    You can implement it so you mark objects for create, update or delete, and later, you call "SaveChanges", "Commit" or any other doing the job of "apply changes", and you'll get done.

    For example, you iterate over the enumerable (oldList) and you mark them as "delete". Later, you call "SaveChanges" and the more abstract, generic unit of work will iterate over the small, filtered list of objects to work with.

    • http://martinfowler.com/eaaCatalog/unitOfWork.html

    Anyway, avoid lists of a milion items. You should work with paged lists of objects.

    0 讨论(0)
  • 2021-01-17 18:05

    The general rule is, you should not modify the same collection in which you are enumerating. If you want to do something like that, keep another collection which will keep track of which elements to add/remove from the original collection and then after exiting from the loop, perform the add/remove operation on the original collection.

    0 讨论(0)
提交回复
热议问题