tags:

views:

70

answers:

3

What is the best way to "reset" a Dictionary<int, bool> type of structure (set all values to true or false). Currently I'm using a ToDictionary() extension method. Is there a way to do this by reusing the current instance?

This code throws an exception:

[TestFixture]
public class Sample
{
    [Test]
    public void SampleTest()
    {
        var dictionary = new Dictionary<int, bool>{{1, false}, {2, true}, {3, false}};
        foreach (var key in dictionary.Keys)
        {
            dictionary[key] = true;
        }

        Assert.That(dictionary[3], Is.True);
    }
}
A: 

You can write your own extension method to work on the existing dictionary.

public static void SetAllValues<TKey,TValue>(this IDictionary<TKey,TValue> dictionary, TValue value) 
{
    foreach(var key in dictionary.Keys.ToList()) 
    { 
        dictionary[key] = value;
    }
}
driis
This throws an InvalidOperationException due to the modification of the collection (***not the downvoter)
Anthony Pegram
Unfortunately, this does not work. You cannot modify the dictionary from within the foreach statement. It throws an InvalidOperationException: "Collection was modified; enumeration operation may not execute.". A trick that would make it work, is to change the foreach:"foreach (var key in dictionary.Keys.ToList())"
Omer Raviv
The code example has been fixed.
driis
+9  A: 
foreach (int key in dictionary.Keys.ToList())
    dictionary[key] = true;
Anthony Pegram
I haven't done any tests, but I think this is unnecessarily creating a List to loop over, while looping over the KeyValuePair's would be faster: `foreach (var kvp in dictionary) dictionary[kvp.Key] = true;`
manixrock
@manixrock, your suggestion throws the same exception, as it attempts to modify the collection being looped over. The point of the call to `ToList` is to create and loop over a different collection entirely.
Anthony Pegram
+2  A: 

As an aside, you might wish to consider using the BitArray class (System.Collections.BitArray). It has a SetAll method that will set all bits to either true or false:

BitArray ba = new BitArray(8);  //BitArray with 8 bits

ba[3] = true;  //set some bits
ba[6] = true;

ba.SetAll(false);  //Clear all

If you don't need a dictionary, you might consider this class.

Chris Dunaway
+1 for BitArray, but in this case it has to be a dictionary (nonsequential ids).
Al Bundy