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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With