C# preventing Collection Was Modified exception

前端 未结 10 1886
梦毁少年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 18:06

    you can use a flag to switch the modification to a temporary list while the original is being enumerated.

    /// where you are enumerating

    isBeingEnumerated = true
    foreach(T value in new List(oldList) )
    isBeingEnumerated = false
    SyncList(oldList with temporaryList)
    

    /// where you are modifying while enumerating

    if isBeingEnumerated then
    use a temporaryList to make the changes.
    

提交回复
热议问题