什么是设置所有的值在C#字典&LT的最佳途径;字符串,布尔&GT;? [英] What's the best way to set all values in a C# Dictionary<string,bool>?
本文介绍了什么是设置所有的值在C#字典&LT的最佳途径;字符串,布尔&GT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是将所有的值在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.
这篇关于什么是设置所有的值在C#字典&LT的最佳途径;字符串,布尔&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文