Navigating through HashTables


Hashtables support an enhanced version of foreach that reports not only the value of each item but also the key for each item.

To navigate through all the items in a HashTable:

  1. Type foreach ( .

  2. Type System.Collections.DictionaryEntry .

  3. Type the name of the variable to hold the current item, for example: current .

  4. Type in table, where table is the variable that points to the HashTable.

  5. Type a close parenthesis ) .

  6. Type an open curly bracket { .

  7. Type current.key to extract the key.

  8. Type current.value to extract the item's value.

  9. Type a close curly bracket } ( Figure 9.61 ).

    Figure 9.61 The foreach support in HashTables returns a DictionaryEntrya structure that reports both the Key and the Value. These two variables are object types, so they need to be casted to a more specific type before using them.
     void Task() {    System.Collections.Hashtable ht = new    System.Collections.Hashtable();    ht.Add("111-11-1111","Bill Cosby");    ht.Add("222-22-2222",    "Robin Williams");    ht.Add("333-33-3333","Chevy Chase");  foreach(System.Collections.   DictionaryEntry en in ht)   {   string key = (string) en.Key;   string name = (string) en.Value;   }  } 

graphics/tick.gif Tip

  • You can also navigate through just the keys or just the values separately ( Figure 9.62 ).

    Figure 9.62 Keys and Values in a HashTable are not limited to strings. You can use any type of object for the Key and for the Value. What's nice is that the foreach statement automatically casts to whatever type you specify for the current item variable. The bad part is that if all the items are not of the same or compatible types, foreach will fail.
     void Task() {    System.Collections.Hashtable ht = new    System.Collections.Hashtable();    ht.Add("111-11-1111","Bill Cosby");    ht.Add("222-22-2222","Robin Williams");    ht.Add("333-33-3333","Chevy Chase");  foreach(string key in ht.Keys)   {   }   foreach(string val in ht.Values)   {   }  } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net