Ok...here's a softball question...
I just need to be able to insert a key/value pair into an object at a specific position. I'm currently working with a Hashtable which, of course, doesn't allow for this functionality. What would be the best approach?
UPDATE: Also, I do need the ability to lookup by the key.
For example...oversimplified and pseudocoded but should convey the point
// existing Hashtable
myHashtable.Add("somekey1", "somevalue1");
myHashtable.Add("somekey2", "somevalue2");
myHashtable.Add("somekey3", "somevalue3");
// Some other object that will allow me to insert a new key/value pair.
// Assume that this object has been populated with the above key/value pairs.
oSomeObject.Insert("newfirstkey","newfirstvalue");
Thanks in advance.
Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>>
or List<KeyValuePair<string, string>>
if you're not using .NET 4.
Use a linked list. It was designed for this exact situation.
If you still need the dictionary O(1) lookups, use both a dictionary and a linked list.
Hashtables are not inherently sorted, your best bet is to use another structure such as a SortedList or an ArrayList
You could use an OrderedDictionary, but I would question why you would want to do that.
Maybe the OrderedDictonary will help you out.
I would use the Dictionary<TKey, TValue>
(so long as each key is unique).
EDIT: Sorry, realised you wanted to add it to a specific position. My bad. You could use a SortedDictionary but this still won't let you insert.
Source: Stackoverflow.com