问题描述
考虑以下代码:
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);
}
我想做的是插入Key3
在Key2
和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?
推荐答案
您可以使用为此。 允许您指定要插入密钥的索引。
You can use an OrderedDictionary
for this. OrderedDictionary.Insert
allows you to specify the index at which the key will be inserted.
这篇关于在特定的地方添加一个字典元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!