Suhas  D

Suhas D

  • NA
  • 199
  • 22.5k

How to swap Hashtable's key with Value.

Jan 16 2013 12:31 AM
How to swap Hashtable's key with Value.
I have solved it by following.
 
Is there any other solution?

class Program
    {
        static void Main(string[] args)
        {
            Hashtable hsTbl = new Hashtable();

            hsTbl.Add(1, "Suhas");
            hsTbl.Add(2, "Madhuri");
            hsTbl.Add(3, "Om");
            List<object> keyList = new List<object>();
            List<object> ValList = new List<object>();

            Console.WriteLine("Key          Value");
            foreach (DictionaryEntry item in hsTbl)
            {
                Console.WriteLine(item.Key + "      " + item.Value);
                keyList.Add(item.Value);
                ValList.Add(item.Key);
            
             }
            hsTbl.Clear()

//Swapping          

  for (int i = 0; i < keyList.Count; i++)
            {
                hsTbl.Add(keyList[i], ValList[i]);
            }

//will display hashtable after swapping

 
            foreach (DictionaryEntry item in hsTbl)
            {
                Console.WriteLine(item.Key + "      " + item.Value);

            }
  }
 }





Answers (3)