C#: Hashtable Inversion, how to invert a Hashtable

This quick project is example of simple Data transformation.  Hashtable’s values containing a comma deliminated list of strings gets turned into a distinct list of keys in another Hashtable.  And, the numbers (keys of initial Hashtable) are accumulated into the values of the new Hashtable.  Creating an inverted Hashtable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace HashInversion
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable num_2_Letters_Hash = new Hashtable();
            Hashtable letters_2_num_Hash = new Hashtable();
 
            num_2_Letters_Hash.Add(1, "a,c,d");
            num_2_Letters_Hash.Add(6, "d,e");
            num_2_Letters_Hash.Add(13, "a,d,j");
            num_2_Letters_Hash.Add(29, "c,e,d");
            num_2_Letters_Hash.Add(7, "j");
            num_2_Letters_Hash.Add(9, "e,c,a");
            num_2_Letters_Hash.Add(11, "c,d,f,j");
 
            foreach (var key in num_2_Letters_Hash.Keys)
            {
                string content = num_2_Letters_Hash[key].ToString();
                string [] letters = content.Split(',');
                for (int i = 0; i < letters.Length; i++)
                {
                    if ( letters_2_num_Hash.ContainsKey(letters[i].ToString()))
                    {
                        string previous_content = letters_2_num_Hash[letters[i]].ToString();
                        letters_2_num_Hash[letters[i]] = previous_content + "," + key;
                    }
                    else
                    {
                        letters_2_num_Hash.Add(letters[i],""+key);
                    }
                }
            }
 
            Console.WriteLine();
 
            Console.WriteLine("before");
            foreach (var key in num_2_Letters_Hash.Keys)
            {Console.WriteLine(key + "   " + num_2_Letters_Hash[key]);}
 
            Console.WriteLine("after");
            foreach (var key in letters_2_num_Hash.Keys)
            {Console.WriteLine(key + "   " + letters_2_num_Hash[key]);}
        }
    }
}

Leave a Reply

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