【问题标题】:Order of printing in Hashtable?哈希表中的打印顺序?
【发布时间】:2014-12-22 07:15:34
【问题描述】:

请参见此处的示例,我按此顺序存储值!但是我得到的输出是不同的!为什么? Hashtable 以什么顺序存储值?

      {               
        Hashtable ht = new Hashtable();
        ht.Add("001", "Zara Ali");
        ht.Add("002", "Abida Rehman");
        ht.Add("003", "Joe Holzner");
        ht.Add("004", "Mausam Benazir Nur");
        ht.Add("005", "M. Amlan");
        ht.Add("006", "M. Arif");
        ht.Add("007", "Ritesh Saikia");

        ICollection key = ht.Keys;

        foreach (string k in key)
         {
            Console.WriteLine(k + ": " + ht[k]);
         }

       }

输出

006: M. Arif
007: Ritesh Saikia
003: Joe Holzner
002: Abida Rehman
004: Mausam Benazir Nur
001: Zara Ali
005: M. Amlan

【问题讨论】:

  • 你可以用SortedDictionary<K, T>代替HashTable

标签: c# .net collections hashtable console.writeline


【解决方案1】:

哈希表不保证其中元素的任何定义顺序。哈希表的实现根据它们的 Hashcode 及其内部实现将值拆分到不同的桶中,这意味着相同的值在不同的机器、不同的运行或不同版本的框架上可能具有不同的顺序。这是因为哈希表针对按键检索而不是按顺序检索进行了优化。

如果您想要一个既可以按键访问又可以按顺序访问的集合,请使用其中一个专门的集合。从您使用Hashtable 而不是Dictionary<K,V> 来看,您可能正在使用.NET 1.1,在这种情况下,您可以使用SortedList,它将在内部保持秩序。较新版本的 .NET 具有 SortedList<K,V>OrderedDictionary<K,V>,它们的性能特征略有不同:

【讨论】:

    【解决方案2】:

    您可以使用SortedDictionary<K, T> 代替过时的HashTable

    SortedDictionary<String, String> ht = new SortedDictionary<String, String>() {
      {"001", "Zara Ali"},
      {"002", "Abida Rehman"},
      {"003", "Joe Holzner"},
      {"004", "Mausam Benazir Nur"},
      {"005", "M. Amlan"},
      {"006", "M. Arif"},
      {"007", "Ritesh Saikia"}
    };
    
    foreach(var pair in ht)
      Console.WriteLine(pair.Key + " " + pair.Value);
    

    因为Dictionary&lt;K, T&gt;Set&lt;T&gt;HashTable(请注意,HashTable 和 ICollection过时不要保持秩序 你必须使用SortedDictionary&lt;K, T&gt;SortedSet&lt;T>。

    【讨论】:

      【解决方案3】:

      Hashtable 不保证任何顺序。您可以使用Dictionary&lt;string, string&gt;,您可以根据需要按值排序。也可以使用SortedDictionary&lt;string, string&gt;,默认按key排序。

              Dictionary<string, string> ht = new Dictionary<string, string>();
              ht.Add("001", "Zara Ali");
              ht.Add("002", "Abida Rehman");
              ht.Add("003", "Joe Holzner");
              ht.Add("004", "Mausam Benazir Nur");
              ht.Add("005", "M. Amlan");
              ht.Add("006", "M. Arif");
              ht.Add("007", "Ritesh Saikia");
      
              var order = ht.OrderBy(x => x.Value);//ht.OrderBy(x => x.Key);
      
              foreach (var k in order)
              {
                  Console.WriteLine(k.Key + ": " + k.Value);
              }
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2012-08-14
        • 2021-12-03
        • 2016-04-09
        • 2015-08-01
        • 2017-08-16
        • 2013-04-18
        • 2022-12-10
        • 1970-01-01
        相关资源
        最近更新 更多