简体   繁体   中英

What's the best way to set all values in a C# Dictionary<string,bool>?

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;
}

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

That is a reasonable approach, although I would prefer:

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

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

单线解决方案:

dict = dict.ToDictionary(p => p.Key, p => false);

如果您不使用三态 bool,则可以使用HashSet<string>并调用Clear()将值设置为“false”。

我不确定这是否是最好的方法,但我正在寻找一条线上的东西,这对我有用

mydict.Keys.ToList().ForEach(k => mydict[k] = false);

I profiled the difference between Billy's and Reed's solutions. Polaris878, take good note of the results and remember that premature optimization is the root of all evil ;-)

I rewrote the solutions in VB (because I'm currently programming in that language) and used int keys (for simplicity), otherwise it's the exact same code. I ran the code with a dictionary of 10 million entries with a value of "true" for each entry.

Billy Witch Doctor's original solution:

Dim keys = dict.Keys.ToList
For i = 0 To keys.Count - 1
    dict(keys(i)) = False
Next

Elapsed milliseconds: 415

Reed Copsey's solution:

For Each key In dict.Keys.ToList
    dict(key) = False
Next

Elapsed milliseconds: 395

So in that case the foreach is actually faster .

Starting from .NET5 (see github ):

foreach (var pair in dict) 
    dict[pair.Key] += 1;

For before .NET5:

foreach (var key in dict.Keys.ToList())
    dict[key] += 1;

You could just pull out the ToList() and iterate directly over the dictionary items

Dictionary<string, bool> dict = GetDictionary();
foreach (var pair in dict) 
{
    dict[pair.Key] = false;
}

Do it the way you have it right now... foreach is slow. foreach may be cleaner, but you take too much of a performance hit using it.


http://www.codeproject.com/KB/cs/foreach.aspx
http://www.madprops.org/blog/for-vs-foreach-performance/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM