Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Todd Main Avatar asked Nov 02 '10 18:11

Todd Main


Video Answer


2 Answers

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.

like image 186
Ruben Avatar answered Sep 28 '22 07:09

Ruben


If this is something that you need to keep track of efficiently, then you are using the wrong data structure. Instead, you should use a SortedDictionary where the key is tagged with the index of when it was added (or a timestamp) and a custom IComparer that compares two keys based on the index (or the timestamp).

like image 35
jason Avatar answered Sep 28 '22 07:09

jason