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

Viewed 39175

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.

8 Answers

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.

If you aren't using tri-state bools, then you can use HashSet<string>, and call Clear() to set the values to "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;
}
Related