F#System.InvalidOperationException:集合被修改; 枚举操作可能无法执行

Fag*_*ain 1 f# dictionary list

我在F#中遇到这个问题[不是C#,其中已有类似的帖子有类似的答案]

我理解它不可能修改一个字典,而在for循环中枚举它我该如何解决?

let edgelist1 = [(1,2,3.0f);(1,2,4.0f);(5,6,7.0f);(5,6,8.0f)]
let dict_edges = new Dictionary<int*int,(int*int*float32) list>()
for x in edgelist1 do dict_edges.Add ((fun (a,b,c)-> (a,b)) x, x)
for k in dict_edges.Keys do dict_edges.[k] <- (dict_edges.[k] |> List.rev)
Run Code Online (Sandbox Code Playgroud)

System.InvalidOperationException:集合已被修改; 枚举操作可能无法执行.

System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource资源)位于System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator.MoveNext()at.$ FSI_0101.main @()

这是有效的

dict_edges.[(1,2)] <- dict_edges.[(1,2)] |> List.rev;;
Run Code Online (Sandbox Code Playgroud)

在for循环中,我只需要更改字典值,而不是键.

谢谢

Fyo*_*kin 5

您可以将所有键复制到临时列表中,然后在修改原始字典时迭代该列表:

for k in (dict_edges.Keys |> Seq.toList) do 
   dict_edges.[k] <- (dict_edges.[k] |> List.rev)
Run Code Online (Sandbox Code Playgroud)

但我强烈建议你重新考虑你的方法并摆脱就地变异.你现在面临的这个小问题只是对基于突变的程序可能出错的第一个品味.