我對F#非常新,在F#中遇到「收集已修改」問題。我知道這個問題在我們迭代集合的同時修改(添加/刪除)它時很常見。並且在stackoverflow中的前面的線程也指向這一點。F#幫助:「收集已修改」
但在我而言,我的工作在2個不同的組: 我有2個類別:
- originalCollection原來的集合。其中我想刪除的東西
- colToRemove集合包含我想要刪除的物體
以下是代碼:
Seq.iter (fun input -> ignore <| originalCollection.Remove(input)) colToRemove
而且我得到以下運行時錯誤: + $例外{System.InvalidOperationException:集合已修改;枚舉操作可能不會執行。 在System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource資源) 在System.Collections.Generic.List 1.Enumerator.MoveNextRare() at System.Collections.Generic.List
1.Enumerator.MoveNext() 在[email protected] [T](FSharpFunc 2 f, IEnumerator
1e中,FSharpRef 1 started, Unit unitVar0) at [email protected]ctions-IEnumerator-MoveNext() at Microsoft.FSharp.Collections.SeqModule.Iterate[T](FSharpFunc
2動作,IEnumerable`1源)
這裏是代碼塊:
match newCollection with
| Some(newCollection) ->
// compare newCollection to originalCollection.
// If there are things that exist in the originalCollection that are not in the newCollection, we want to remove them
let colToRemove = Seq.filter (fun input -> Seq.exists (fun i -> i.id = input.id) newCollection) originalCollection
Seq.iter (fun input -> ignore <| originalCollection.Remove(input)) colToRemove
| None ->()
謝謝!
注意:在此處使用單線程環境,因此不存在可能導致此異常的多線程問題。