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

是否有方法或技术允许您将元素插入到Dictionary ,以保证该项位于该字典的KeyCollection的第一个索引中。

例如:

 Dictionary 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 key in dic) { Console.WriteLine("{0} = {1}", key.Key, key.Value); } 

输出:

 key = value foo = baa a = b 

很感谢任何forms的帮助。 提前致谢!

不使用字典。

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

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

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

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

您可能需要的是List ,其元素可以插入到特定索引中。

 List> list = dic.ToList(); list.Insert(0, new KeyValuePair("a", "b")); foreach(KeyValuePair pair in list) Console.WriteLine("{0} = {1}", pair.Key, pair.Value); 

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

 Dictionary dic = foo.GetOutput(); dic = (new Dictionary {{"key","value"}}).Concat(dic).ToDictionary(k => k.Key, v => v.Value); 

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

Dictionary无法实现这一点Dictionary因为它在枚举时以无序方式显示它的值。 SortedDictionary提供排序,但它通过直接使用IComparer对键值进行排序。 在这里,您希望键是一个String并且基于int进行排序。 对于这两种类型中的任何一种都不可能。

我认为您需要在其中实现具有这些非常特定语义的新类型。 例如。

 class OrderedMap { private readonly Dictionary _map = new Dictionary(); private readonly List _list = new List(); public void Add(TKey key, TValue value) { if (!_map.ContainsKey(key)) { _list.Add(key); } _map[key] = value; } public void Add(TKey key, TValue value, int index) { if (_map.ContainsKey(key)) { _list.Remove(key); } _map[key] = value; _list.Insert(index, key); } public TValue GetValue(TKey key) { return _map[key]; } public IEnumerabe> GetItems() { foreach (var key in _list) { var value = _map[key]; yield return new KeyValuePair(key, value); } } } 

请注意,与传统的Dictionary这确实存在一些非平凡的性能差异。 例如, AddRemove速度较慢。

Dictionary本质上是无序的(或者更确切地说,排序是不可预测的,不应该依赖它)。 如果您想要某种排序,则需要使用其他类型。 如果不了解您的要求,很难推荐任何特定类型。

无法订购Dictionary

你可以尝试使用SortedDictionary ,但是那个是按Key排序的,而不是单独的索引。

Dictionary类不按顺序保存项目,因此没有“第一”项。

有一个SortedDictionary (.NET 4.0+),它按键排序,但同样,这是一个非常模糊的“第一”概念。

Dictionary是一种无序的集合。 你可以尝试OrderedDictionaryhttp://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx – 它有一个Insert()方法,这就是你所追求的。

这是我的解决方案,也许不是最好的解决方案,但它有效。 =)

 public static ComboBox FillDropDownList(Dictionary dictionary, ComboBox dropDown, String selecione) { var d = new SortedDictionary(); d.Add("0", selecione); foreach (KeyValuePair pair in dictionary) { d.Add(pair.Key, pair.Value); } dropDown.DataSource = new BindingSource(d, null); dropDown.DisplayMember = "Value"; dropDown.ValueMember = "Key"; dropDown.SelectedIndex = 0; return dropDown; }