在特定位置添加字典元素

Ice*_*ind 3 c# dictionary

请考虑以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是插入"Key3"之间"Key2""Key4".为简单起见,我以此为例.我知道我可以使用SortedDictionary,我可以让这个例子起作用.我需要能够具体做的是,每当我在字典中插入一个新元素时,我总是希望它在第二个元素之后和第三个元素之前插入它.我怎么能做到这一点?

Jon*_*Jon 11

你可以使用一个OrderedDictionary.OrderedDictionary.Insert允许您指定要插入密钥的索引.