With ListDictionary, we can Add and Remove elements and use the Count property. The key difference is in its performance characteristics.
using System;
using System.Collections;
// For Hashtable.
using System.Collections.Specialized;
// For ListDictionary.
using System.Diagnostics;
class Program
{
static void Main()
{
ListDictionary list = new ListDictionary();
list.Add(
"dot", 1);
list.Add(
"net", 2);
list.Add(
"perls", 3);
Hashtable hash = new Hashtable();
hash.Add(
"dot", 1);
hash.Add(
"net", 2);
hash.Add(
"perls", 3);
Console.WriteLine(
"ListDictionary.Count: {0}", list.Count);
Console.WriteLine(
"Hashtable.Count: {0}", hash.Count);
Console.WriteLine();
const int max = 10000000;
// Version 1: use ListDictionary.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
object a = list[
"perls"];
}
s1.Stop();
// Version 2: use Hashtable.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
object a = hash[
"perls"];
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString(
"ListDictionary: 0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString(
"Hashtable: 0.00 ns"));
}
}
ListDictionary.Count: 3
Hashtable.Count: 3
ListDictionary: 17.69 ns
Hashtable: 51.14 ns