哈希表加扰

本文关键字:哈希表 | 更新日期: 2023-09-27 18:20:30

我的应用程序上有以下哈希表:

System.Collections.Hashtable colunas = new System.Collections.Hashtable();
colunas.Add("Nome", "Nome");
colunas.Add("Departamento", "Departamento");
colunas.Add("Cargo", "Cargo");

之后,我将这个哈希表作为参数传递给一个函数,当我在foreach中传递哈希表时,我得到以下结果:

Departamento
Nome 
Cargo

为什么结果是按这个顺序而不是按这个顺序:

Nome
Departamento
Cargo

--编辑--

好的,我理解原因,但我可以用什么代替哈希表来保持插入顺序?

哈希表加扰

哈希表不保留插入顺序。

相反,它们使用基于键的哈希代码的未指定顺序。

这个答案是根据原始海报的请求从评论中"提升"出来的。

如果保持插入顺序对您来说很重要,那么您可能希望简单地使用List<>,它的元素在某种程度上是成对的字符串。两种解决方案都是自然的:

var colunas = new List<KeyValuePair<string, string>>();
colunas.Add(new KeyValuePair<string, string>("Nome", "Nome"));
colunas.Add(new KeyValuePair<string, string>("Departamento", "Departamento"));
colunas.Add(new KeyValuePair<string, string>("Cargo", "Cargo"));

或:

var colunas = new List<Tuple<string, string>>();
colunas.Add(Tuple.Create("Nome", "Nome"));
colunas.Add(Tuple.Create("Departamento", "Departamento"));
colunas.Add(Tuple.Create("Cargo", "Cargo"));

KeyValuePair<,>Tuple<,>之间存在技术差异,因为前者是struct(值类型),后者是class(引用类型),但由于KeyValuePair<,>Tuple<,>都是不可变的类型,这可能并不重要。然后决定属性名称Key/Value还是Item1/Item2最适合您使用。

请注意,如果使用此解决方案,则无法获得哈希表提供的好处。您无法快速查找密钥。并且不能保证List<>不能有多个条目具有相同的"键"字符串(对中的第一个组件)。这个字符串甚至可能是null

如果您想对List<>进行排序,那么在某个时刻,调用colunas.Sort();(未给出比较器参数)将适用于Tuple<,>(字典顺序),但不适用于KeyValuePair<,>。当然,如果您希望集合始终按键排序,您可以按照另一个答案的建议使用SortedDictionary<string, string>

Hashtable表示基于键的哈希代码组织的键/值对的集合。

但是我可以用什么来代替hashtable来保持插入顺序呢?

您可以选择:

  • System.Collections.Generic.SortedList<TKey, TValue>
  • System.Collections.Generic.SortedDictionary<TKey, TValue>

请参阅此处的备注部分了解差异。