如何在字典中的第一个索引插入元素? [英] How to insert element in first index in dictionary?

查看:688
本文介绍了如何在字典中的第一个索引插入元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有方法或技术,可让您元素插入到
词典< TKEY的,TValue> 确保该项目是第一个索引。那字典的KeyCollection

Is there a method or technique that allows you to insert an element into a Dictionary<TKey, TValue> guaranteeing that the item is in the first index of that dictionary's KeyCollection.

例如:

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

// `dic` is something like:

// {"foo", "baa"},
// {"a", "b"}

我需要的是这样的:

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



输出:

Output:

key = value
foo = baa
a = b

任何帮助是非常赞赏。在此先感谢!

Any help is very much appreciated. Thanks in advance!

推荐答案

由于不使用字典。

词典< TKEY的,TValue> 被实现为哈希表。内部的字典键的位置取决于哈希码,其中该散列码减少进一步提供一种索引,其内部结构的装置,和插入在一个完全依赖于实现方式的顺序。

Dictionary<TKey, TValue> is implemented as a hash-table. The position of keys internal to the dictionary depends upon the hash-code, the means by which that hash-code was reduced further to provide an index into its internal structure, and the order of insertion in an entirely implementation-dependant way.

这并不是实现一个字典的唯一途径。 SortedDictionary< TKEY的,TValue> 内部使用一个树状结构,因此始终保持键的顺序。在这种情况下,我们仍然不能在开头插入一些东西,而我们插入的东西,它被放置在适当的位置。

This isn't the only way to implement a dictionary. SortedDictionary<TKey, TValue> uses a tree structure internally and so always keeps keys in an order. In this case we still can't insert something in the beginning, rather we insert something and it gets put in the appropriate place.

如果排序是你最关心什么,那么你不想puredictionary的。而你想无论是列表< KeyValuePair< TKEY的,TValue>> 或你想要,提供了一个list的两个功能的字典,它是通过提供和结构 OrderedDictionary 。这不是通用的,但你可以很容易地创建一个通用的包装它周围的(不给内部使用泛型的性能优势,但确实给使用类型安全)。

If ordering is what you care about most, then you don't want a puredictionary at all. Rather you want either a List<KeyValuePair<TKey, TValue>> or you want a structure that offers both the functionality of a list and of a dictionary, which is provided by OrderedDictionary. This isn't generic, but you can easily create a generic wrapper around it (doesn't give the performance benefits of internally using generics, but does give type-safety in use).

这篇关于如何在字典中的第一个索引插入元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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