繁体   English   中英

遍历字典并将值添加到每个字典值

[英]Iterating through a Dictionary and adding a value to every dictionary value

我想在字典中的每个值上加1。

产生“ InvalidOperationException:不同步”

    public Dictionary<int,int> dict = new Dictionary<int,int>();
    dict.Add (23, 34);

foreach (KeyValuePair<int,int> kvp in dict) {
        dict [kvp.Key] += 1;
    }

这是完整的错误消息:

System.Collections.Generic.Dictionary`2+Enumerator[System.Int32,System.Int32].VerifyState () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:912)
System.Collections.Generic.Dictionary`2+Enumerator[System.Int32,System.Int32].MoveNext () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:835)

这种尝试给出了类似的结果:

foreach (int x in dict.Keys) {
            kek [x] += 1;
        }

尝试:

foreach (int x in dict.Keys.ToList()) {
    dict[x] += 1;
}

因为字典因更改(以及其内部迭代器)而失效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM