The use of Hashtable in C#

  1. Basic operation

Hashtable namespace System.Collections, introduced by using.

//Instantiate Hashtable 
            Hashtable hashTable = new Hashtable();
             //Add elements 
            hashTable.Add( "1" , "Xianxiuyun" );
            hashTable.Add( "2" , "Xianxiuyun-Solution Library" );
            hashTable.Add( "2" , "Xianxiuyun-IT Knowledge Base" );
             //Remove elements 
            hashTable.Remove( "1" );
             //Remove all elements
            hashTable.Clear();
            // number of elements
            int count=hashTable.Count;
            //Determine whether it contains key 
            Boolean isKey= hashTable.ContainsKey( "1" );
             //Determine whether it contains value 
            Boolean isValue= hashTable.ContainsValue( "Xianxiuyun" );

  1. Traversal of Hashtable The common traversal of Hashtable is divided into key-key traversal, value traversal and key-value pair traversal.

//key traversal 
            foreach (String key in hashTable.Keys)
            {
                Console.WriteLine(hashTable[key].ToString());
            }
            //value traversal 
            foreach (String value  in hashTable.Values)
            {
                Console.WriteLine(value);
            }
            //Key-value pair KeyValuePair<T,K> traverse 
            foreach (KeyValuePair<String , String > kv in hashTable)
            {
                Console.WriteLine(kv.Key + kv.Value);
            }

  1. Hashtable sorting Sometimes Hashtable needs to be sorted by key, and Hashtable cannot be sorted directly due to its own implementation. Here you can sort by workarounds.

//Instantiate an ArrayList object, and assign the keys of Hashtable 
            ArrayList akeys = new ArrayList(hashTable.Keys);
             //Sorting alphabetically by Key, ArrayList Sort can also specify a range for sorting
            akeys.Sort(); 
            //sorted traversal output 
            foreach ( string skey in akeys )
            {
               Console.WriteLine(hashTable[skey]);
            }

Hashtable itself does not support sorting, and can be replaced with Dictionary if allowed in the program.

Leave a Comment

Your email address will not be published. Required fields are marked *