在特定位置添加一个词典元素 [英] Adding a dictionary element at a specific place
问题描述
考虑下面的代码:
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);
}
我想要做的就是插入密钥3
之间密钥2
和KEY4
。我用这作为简单起见一个例子。我知道我可以用一个SortedDictionary,我能得到这个例子的工作。我需要能够专门做的虽然是,每当我插入一个新元素到字典,我总是希望它的第二个元素后第三元素之前插入。我怎样才能做到这一点?
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?
推荐答案
您可以使用的 OrderedDictionary
这一点。 OrderedDictionary.Insert
允许你指定在该密钥将被插入的索引。
You can use an OrderedDictionary
for this. OrderedDictionary.Insert
allows you to specify the index at which the key will be inserted.
这篇关于在特定位置添加一个词典元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!