using System.Collections.Generic;
public static void Main()
var hashTable = new DynamicHashtable<int>();
hashTable.Add("three", 3);
hashTable.Add("four", 4);
var one = hashTable.Get("one");
var two = hashTable.Get("two");
var three = hashTable.Get("three");
var four = hashTable.Get("four");
Console.WriteLine($"One: {one}");
Console.WriteLine($"Two: {two}");
Console.WriteLine($"Three: {three}");
Console.WriteLine($"Four: {four}");
public int Hash {get;set;}
public string Key {get;set;}
public T Value {get;set;}
public Node<T> Next {get;set;}
public class DynamicHashtable<T>
private readonly IList<Node<T>> buckets;
public DynamicHashtable()
buckets = new List<Node<T>>();
foreach(var head in buckets)
Console.WriteLine("Nothing found in this bucket");
Console.WriteLine($"Head Element {currentHead.Key} : {currentHead.Value}");
while(currentHead.Next != null)
currentHead = currentHead.Next;
Console.WriteLine($"Child Element {currentHead.Key} : {currentHead.Value}");
public void Add(string key, T toAdd)
throw new Exception("Cannot use an empty key!");
var bucketHash = GetBucketHash(key);
var targetBucket = buckets.SingleOrDefault(b => b.Hash == bucketHash);
var newNode = new Node<T>
Console.WriteLine($"Brand new key {bucketHash} for value: {toAdd}");
Console.WriteLine($"Existing key {bucketHash} for value: {toAdd}");
var lastChild = GetLastBucketChild(targetBucket);
lastChild.Next = newNode;
throw new Exception("Cannot use an empty key!");
var node = GetNodeByKey(key);
throw new Exception("Cannot find any node by that key!");
private Node<T> GetNodeByKey(string key)
var bucketHash = GetBucketHash(key);
var currentNode = buckets[bucketHash];
while(currentNode != null)
if(currentNode.Key == key)
currentNode = currentNode.Next;
private Node<T> GetLastBucketChild(Node<T> bucketStart)
var lastNode = bucketStart;
while(lastNode.Next != null)
lastNode = lastNode.Next;
private int GetBucketHash(string key)
Console.WriteLine($"Provided key: {key}; hashcode: {key.GetHashCode()}; buckets length: {buckets.Count}");
var computedHashcode = buckets.Count == 0 ? 0 : Math.Abs(key.GetHashCode() % buckets.Count);
Console.WriteLine($"Provided key: {key} computed hashcode: {computedHashcode}");
private bool ValidateKey(string key)
return !string.IsNullOrWhiteSpace(key);