How To Iterate the Hashtable in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eliza64

    How To Iterate the Hashtable in C#

    If we write this for the hashtable then we would not get the desired values.
    Code:
      Hashtable ss = new Hashtable();
      ss["key1"] ="india";
      ss["key2"] = "bharat";
     
      foreach (object gg in ss)
      {
        Console.WriteLine("Key value is " + gg);
        Console.Read();
      }
    Here we get System.Collecti ons.DictionaryE ntry and System.Collecti ons.DictionaryE ntry as output instead of the value pairs stored in the hashtable.

    In this case we can help of DictinaryEntry object for iterating the hashtable.

    Code:
    foreach(DictionaryEntry gg in ss)
    {
      Console.WriteLine("Key  and  value are " + gg.Key + "   "  + gg.Value);
      Console.Read();
    }
    A DictionaryEntry object is simply a container containing the Key and Value .
    Last edited by Frinavale; Mar 22 '10, 04:14 PM. Reason: Please post code in [code] ... [/code] tags.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Moving to the .NET forum.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      This thread never made it to the C# or .NET forum...
      I'm not sure what the problem is but in the first example you aren't using the HashTable Object properly. A HashTable is a collection of Key-Value pairs. To access a value you must supply the key to the HashTable.

      It's no wonder why your code didn't work

      Here's a working example of how you're supposed to use a HashTable (printing all Key-Value pairs)

      Code:
      Hashtable ss = new Hashtable();
      ss["key1"] ="india";
      ss["key2"] = "bharat";
        
      foreach (string gg in ss.Keys)
      {
        Console.WriteLine("Key: " + gg + " Value: " + ss[gg]);
        Console.Read();
      }
      -Frinny

      Comment

      Working...