Kimi
Kimi

Reputation: 14099

Set all values of IDictionary

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

Upvotes: 2

Views: 762

Answers (2)

Chris Dunaway
Chris Dunaway

Reputation: 11216

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.

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126932

foreach (int key in dictionary.Keys.ToList())
    dictionary[key] = true;

Upvotes: 11

Related Questions