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


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


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »