How To Iterate A Hashtable Using C#


Have you ever wanted to iterate a Hashtable?



Hashtable myHashTable = new Hashtable();

myHashTable.Add("ES", 1);
myHashTable.Add("EN", 2);
myHashTable.Add("FR", 4);
myHashTable.Add("RU", 3);

//now go through our hash
foreach (object obj in myHashTable.Keys)
     //check for the value is 4
     if ((int)myHashTable[obj] == 4)
          //do something

     Console.WriteLine(String.Format("Key: {0}, Value: {1}", obj, myHashTable[obj]));



The application of this example may not make sense, but it was to illustrate how to iterate a Hashtable, and analyse the value of a key.  A real life applicaiton could be that I have a document that has 4 sections.  A source delivers it in numerous languages, and each language may or may not have all of the sections populated.  I need to keep track of which lanugage has populated sections, so that I can display the most populated version of the document.  In this case I would store the language in the Hashtable as the Key, and then when I get a section, I can simply increment the Value for the Key (in this case the language).  When my loading of the document is complete I can then get the Language for the most populated section, and then do things, like display a flag or somethine else.

Pingbacks and trackbacks (1)+

Add comment

  Country flag

  • Comment
  • Preview