什么是将所有的值在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.