在特定的地方添加一个字典元素 [英] Adding a dictionary element at a specific place

查看:91
本文介绍了在特定的地方添加一个字典元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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 Key2Key4之间。为了简单起见,我以此为例。我知道我可以使用一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆