开发者

How to change all values in a Dictionary<string, bool>?

So I have a Dictionary<string, bool> and all I want to do is 开发者_StackOverflow中文版iterate over it and set all values to false in the dictionary. 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

foreach (string key in new List<TKey>(parameterDictionary.Keys))
  parameterDictionary[key] = false;


In .net 5 the following snippet no longer throws:

var d = new Dictionary<string, int> { { "a", 0 }, { "b", 0 }, { "c", 0 }};

foreach (var k in d.Keys){
      d[k] = 1;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜