c# - 在特定位置添加字典元素

标签 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);
}

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

最佳答案

您可以使用 OrderedDictionary为了这。 OrderedDictionary.Insert允许您指定将插入 key 的索引。

关于c# - 在特定位置添加字典元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918328/

相关文章:

c# - 线程安全的异步字节队列

java - 在 java 中使用 HashMap 的主要好处是什么?

c# - 使用 Ajax 以 guid 作为键的 .NET MVC 字典绑定(bind)问题

c# - 为什么递归构造函数调用会使无效的 C# 代码编译?

c# - 具有编程依赖注入(inject)的 Asp.Net Core 规则引擎 - 未找到类型 'type' 的构造函数

python - 将 .txt 文件处理成字典 (Python v2.7)

java - 从任何给定的日期间隔返回一周的 1 到 7 天

python - 在模拟上调用 python 内置 dict

c# - 如何在 winforms 中第二次显示表单 "smoothly"?

C# 从 C malloc 释放 IntPtr