Consider the following code:
var myDict = new Dictionary<string, int>();
myDict.Add("Key1", 1);
myDict.Add("Key2", 2);
myDict.Add("Key4", 4);
myDict.Add("Key5", 5);
foreach (KeyValuePair<string, int> pair in myDict)
{
Console.Write(pair.Key + @" --> ");
Console.WriteLine(pair.Value);
}
myDict.Add("Key3", 3);
foreach (KeyValuePair<string, int> pair in myDict)
{
Console.Write(pair.Key + @" --> ");
Console.WriteLine(pair.Value);
}
What I want to do is insert "Key3"
in between "Key2"
and "Key4"
. I am using this as an example for simplicity's sake. I know I could use a SortedDictionary and I could get this example to work. What I need to be able to do specifically though is, whenever I insert a new element into the dictionary, I ALWAYS want it to insert it after the 2nd element and before the 3rd element. How can I accomplish this?