Search code examples
c#.netvb.netcollectionshashtable

Sorting Hashtable by Order in Which It Was Created


This is similar to How to keep the order of elements in hashtable, except for .NET.

Is there any Hashtable or Dictionary in .NET that allows you to access it's .Index property for the entry in the order in which it was added to the collection?


Solution

  • A NameValueCollection can retrieve elements by index (but you cannot ask for the index of a specific key or element). So,

    var coll = new NameValueCollection();
    coll.Add("Z", "1");
    coll.Add("A", "2");
    Console.WriteLine("{0} = {1}", coll.GetKey(0), coll[0]); // prints "Z = 1"
    

    However, it behaves oddly (compared to an IDictionary) when you add a key multiple times:

    var coll = new NameValueCollection();
    coll.Add("Z", "1");
    coll.Add("A", "2");
    coll.Add("Z", "3");
    Console.WriteLine(coll[0]); // prints "1,3"
    

    The behaviour is well documented, however.

    Caution: NameValueCollection does not implement IDictionary.


    As an aside: Dictionary<K,V> does not have any index you can use, but as long as you only add elements, and never remove any, the order of the elements is the insertion order. Note that this is a detail of Microsoft's current implementation: the documentation explicitly states that the order is random, so this behavior can change in future versions of the .NET Framework or Mono.