When to use a HashTable

Maybe not directly related to the OPs question, but there's a useful blog post about which collection structure to use at: SortedSets

Basically, what you want to do with the collection determines what type of collection you should create.

To summarise in more detail:

  • Use IList if you want to be able to enumerate and / or modify the collection (normally adding at end of list)
  • Use IEnumeration if you just want to enumerate the collection (don't need to add / remove - usually used as a return type)
  • Use IDictionary if you want to access elements by a key (adding / removing elements quickly using a key)
  • Use SortedSet if you want to access a collection in a predefined order (most common usage being to access the collection in order)

  • Overall, use Dictionary if you want to access / modify items by key in no particular order (preferred over list as that's generally done in order, preferred over enumeration as you can't modify an enumeration, preferred over hashtable as that's not strictly typed, preferred over sortedlist when you don't need keys sorted)


You use a hashtable (dictionary) when you want fast look up access to an item based on a key.

If you are using List, IList or IEnumerable generally this means that you are looping over data (well in the case of IEnumerable it definitely means that), and a hashtable isn't going to net you anything. Now if you were looking up a value in one list and using that to access data in another list, that would a little different. For example:

  1. Find position in list of Item foo.
  2. Position in list for foo corresponds to position in another list which contains Foo_Value.
  3. Access position in seconds list to get Foo_Value.

Here is a link describing the different datatypes.

Another link.


Hash-tables are good choices if you are often doing "for something in collection" and you aren't concerned about the order of items in the collection.

Hash-tables are indexes. You can maintain a hash-table to index a list, so you can both choice to access it in order or randomly based upon the key.


Use a hashtable, when you need to be able to (quickly) look up items by key.

Of course, you can search through an IList or IEnumerable etc for a matching key but that will take O(n) time rather than O(1) for Hashtable or Dictionary.

Tags:

C#