如何在字典中的第一个索引中插入元素?

Jac*_*ack 16 .net c# dictionary

是否有一种方法或技术允许您插入元素以 Dictionary<TKey, TValue>保证该项位于该字典的KeyCollection的第一个索引中.

例如:

Dictionary<String, String> dic = foo.GetOutput(); 

// `dic` is something like:

// {"foo", "baa"},
// {"a", "b"}
Run Code Online (Sandbox Code Playgroud)

我需要这样的东西:

dic.Add("key", "value", 0);
// where `0` is the index that `key` to be inserted.

foreach(KeyValuePair<String, String> key in dic) 
{
     Console.WriteLine("{0} = {1}", key.Key, key.Value);
}
Run Code Online (Sandbox Code Playgroud)

输出:

key = value
foo = baa
a = b
Run Code Online (Sandbox Code Playgroud)

很感谢任何形式的帮助.提前致谢!

Jon*_*nna 23

不使用字典.

Dictionary<TKey, TValue>实现为哈希表.字典内部的键的位置取决于散列码,散列码进一步减少以提供其内部结构的索引的方式,以及完全依赖于实现的方式的插入顺序.

这不是实现字典的唯一方法.SortedDictionary<TKey, TValue>在内部使用树结构,因此始终保持按顺序.在这种情况下,我们仍然不能在开头插入一些东西,而是插入一些东西,然后将它放在适当的位置.

如果订购是您最关心的,那么您根本不需要puredictionary.相反,您想要一个List<KeyValuePair<TKey, TValue>>或者您想要一个既提供列表功能又提供字典功能的结构OrderedDictionary.这不是通用的,但您可以轻松地围绕它创建一个通用的包装器(不会提供内部使用泛型的性能优势,但确实使用了类型安全性).

  • @Keren,不,字典没有依赖于`Key` 的顺序。一方面,可以使用与“Key”不可比较的类型,如果字典需要对它们进行排序,这是不可能的。 (2认同)

MJK*_*MJK 9

我知道这是一个三年前的问题.但找到了解决这个问题的方法.它可能会帮助某人

Dictionary<String, String> dic = foo.GetOutput();

dic = (new Dictionary<string, string> {{"key","value"}}).Concat(dic).ToDictionary(k => k.Key, v => v.Value);
Run Code Online (Sandbox Code Playgroud)

这将在字典的开头插入元素:)

  • 这是一个实现细节,如果字典调整其内部数组的大小,则不能保证第一个项目将保留第一个项目。 (2认同)

Ada*_*kis 8

字典是无序的; 元素意味着使用键检索,其哈希值指向其值的位置.

你可能想要的是a List <KeyValuePair>,其元素可以插入到特定的索引中.

List<KeyValuePair<string, string>> list = dic.ToList();
list.Insert(0, new KeyValuePair<string, string>("a", "b"));

foreach(KeyValuePair<string, string> pair in list)
    Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
Run Code Online (Sandbox Code Playgroud)