Thursday, September 17, 2009

C# - Hashtable and ArrayList

What is “Hashtable”? What are the benefits of it over Arraylist?
I am thinking of using Arraylist or Hashtable to group and then sort near about 100000 of records. Which collection will be better option for me? Why?

Hashtable is one type of collection supported by C#. It’s a collection of items in key value pair. Every item in the Hashtable has a key with pointer to its linked value. The key and the value can be any object. Key must be unique value. Hashtable is useful when you need to store data in a key and value pair.

A Hashtable is better for looking up values based on the key, but you can't really sort it - it maintains its own 'internal sort' to optimize the lookups.

So, if you want to lookup values then it's better to use a Hashtable, if you want to sort all the items into a particular order then use the Arraylist.

A wrapper class can be designed that will make use of internal hashtable to provide search on items and a list for iteration and sorting.

Trick for rapid fire developers to get items sorted from hashtable:
Hashtable h = new Hashtable();
h.Add(1, 1);
h.Add(2, 5);
h.Add(3, 3);
ArrayList l = new ArrayList(h.Values);
*Values in hashtable should be numeric values.

.NET 2.0 also offers Dictionary collection. It is a mix between hashtable (sort and identify objects of any type by a key) and an Arraylist (objects of a specified type).

No comments:

Post a Comment