什么是设置所有的值在C#字典&LT的最佳途径;字符串,布尔>?有的、布尔、字符串、字典

2023-09-04 07:10:23 作者:满天繁星不及你的回眸

什么是将所有的值在C#字典的最佳方式是什么?

What's the best way to set all values in a C# Dictionary?

下面是我在做什么,但我敢肯定有一个更好/更清洁的方式做到这一点:

Here is what I am doing now, but I'm sure there is a better/cleaner way to do this:

Dictionary<string,bool> dict = GetDictionary();
var keys = dict.Keys.ToList();
for (int i = 0; i < keys.Count; i++)
{
    dict[keys[i]] = false;
}

我已经尝试了一些其他的方式用foreach,但我有错误。

I have tried some other ways with foreach, but I had errors.

推荐答案

这是一种合理的做法,但我会preFER:

That is a reasonable approach, although I would prefer:

foreach (var key in dict.Keys.ToList())
{
    dict[key] = false;
}

到了ToList()的调用,使这项工作,因为它拉出和(临时)节能键列表,所以迭代的作品。

The call to ToList() makes this work, since it's pulling out and (temporarily) saving the list of keys, so the iteration works.