HashTable Class

Overview

  • Key-value pair based collection.
  • Contains DictionaryEntry objects.
  • Not accessible by index, only by key.
  • Values are returned based on the hash value when doing a foreach.
  • Internally uses hashes to store objects, derived from the GetHashCode method on each object.
    • Hashes are used for equality of objects.
    • No duplicate hashes can occur.

Good practice

  • When possible, use a generic collection instead of the object-based HashTable.
  • Implement GetHashCode and Equals in custom objects when you need HashTable to treat objects as the same.
  • Use a ListDictionary or HybridDictionary when working with smaller collections than 10 or unknown size collections.

Examples

Adding and Removing Elements

Hashtable a = new Hashtable();
a.Add("Key1", "Hello");
a.Add("Key2", "World");
a.Add("Key0", "Start");
Console.WriteLine(a["Key1"] + " " + a["Key2"]);
foreach (DictionaryEntry d in a) { Console.WriteLine(d.Value); }
foreach (var v in a.Values) { Console.WriteLine(v); }
 
a.Remove("Key1");
foreach (var k in a.Keys) { Console.WriteLine(a[k]); }
 
learning/exam70-536/hashtable.txt · Last modified: 2008/09/16 15:48 by david
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki