Coding Index Lookup Functions using C# Hashtables

A very common coding task is creating some way to lookup the index of an object of some kind. For example, suppose you have an array of n strings (or an array of just about anything) and you want a function which accepts a string and returns the index of that string (a number between 0 and n-1). So for example if you have the 4 names “Adams”, “Brown”, “Cheng”, “Dunne” and the desired function accepts a name like “Cheng” and returns its associated index (2). If the size of the array of objects is large, one good approach is to construct a Hashtable and use it as in the following example:
using System;
using System.Collections; // Hashtable
namespace HashtableDemo
  class Program
    static Hashtable ht = null;
    static void Main(string[] args)
      string[] names = new string[] { "Brown", "Dunne", "Adams", "Cheng" };
      Console.WriteLine("\nCreating lookup hash table");
      ht = new Hashtable();
      for (int i = 0; i < names.Length; ++i)
        int theKey = names[i].GetHashCode();
        int theValue = i;
        if (ht.Contains(theKey) == false)
          ht.Add(theKey, theValue);
      Console.WriteLine("The index of ‘Cheng’ is " + GetNameIndex("Cheng"));
    } // Main()
    static int GetNameIndex(string name)
      int theKey = name.GetHashCode();
      return (int)ht[theKey];
The output is shown in the image below.
This entry was posted in Software Test Automation. Bookmark the permalink.