Monday, 4 May 2015

Hashtable

A hashtable is a data structure that maps key value pairs. A hashtable leverages a hash function to compute an index into an array of slots, from which the value can be found.

You can think of it as an array that uses a function to get it's index from a key. here's a more in depth explanation. now for large data sets especially ones that have a unique key this data structure is perfect.

using System;
using System.Collections;

namespace pc.hashtableexample
{
class Program
{
public class Person
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public Person(string Name, DateTime BirthDate)
{
this.Name = Name;
this.BirthDate = BirthDate;
}
public int GetAge()
{
DateTime today = DateTime.Today;
int age = today.Year - BirthDate.Year;
return BirthDate > today.AddYears(-age) ? --age : age;
}

public override string ToString()
{
return Name + " is " + GetAge();
}
}

static void Main(string[] args)
{
var ht = new Hashtable();

//add key and item
ht.Add(2, new Person("Pawel", new DateTime(1984, 01, 31)));
ht.Add("bla", new Person("Tom", new DateTime(1988, 08, 28)));
ht.Add(3.0, new Person("Magda", new DateTime(1984, 06, 28)));

Console.WriteLine(ht["bla"]);
Console.WriteLine(ht[2]);
Console.WriteLine(ht[3]);
Console.WriteLine(ht[3.0]);
}
}
}


Above you can see how simple it is to use the hash table data-structure, just keep in mind the following: 
  •  calling fr a key that doesn't exist return null, 
  •  anything that derives from object can be a key 
  • one last caveat is that the key must be unique