[英]How to change all values in a Dictionary<string, bool>?
So I have a Dictionary<string, bool>
and all I want to do is iterate over it and set all values to false in the dictionary.所以我有一个Dictionary<string, bool>
,我想做的就是遍历它并将字典中的所有值设置为 false 。 What is the easiest way to do that?最简单的方法是什么?
I tried this:我试过这个:
foreach (string key in parameterDictionary.Keys)
parameterDictionary[key] = false;
However I get the error: "Collection was modified; enumeration operation may not execute."但是我收到错误消息:“集合已修改;枚举操作可能无法执行。”
Is there a better way to do this?有一个更好的方法吗?
Just change the enumeration source to something other than the dictionary.只需将枚举源更改为字典以外的其他内容。
foreach (string key in parameterDictionary.Keys.ToList())
parameterDictionary[key] = false;
For .net 2.0对于 .net 2.0
foreach (string key in new List<TKey>(parameterDictionary.Keys))
parameterDictionary[key] = false;
In .net 5 the following snippet no longer throws:在 .net 5 中,以下代码段不再抛出:
var d = new Dictionary<string, int> { { "a", 0 }, { "b", 0 }, { "c", 0 }};
foreach (var k in d.Keys){
d[k] = 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.