考虑以下代码:
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);
}
我想要做的是在"Key2"
和"Key4"
之间插入"Key3"
。为简单起见,我以此为例。我知道我可以使用 SortedDictionary 并且我可以让这个例子工作。不过,我需要具体做的是,每当我向字典中插入一个新元素时,我总是希望它在第二个元素之后和第三个元素之前插入它。我怎样才能做到这一点?
最佳答案
您可以使用 OrderedDictionary
为了这。 OrderedDictionary.Insert
允许您指定将插入 key 的索引。
关于c# - 在特定位置添加字典元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918328/