C# 中 Dictionary 和 Hashtable 之間的區別


Hashtable 比 Dictionary 慢。對於強型別集合,Dictionary 集合更快。

Hashtable

Hashtable 類表示一個鍵值對集合,該集合是根據鍵的雜湊碼進行組織的。它使用鍵來訪問集合中的元素。

讓我們看一個示例 −

示例

 即時演示

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Hashtable ht = new Hashtable();

         ht.Add("E001", "Tom");
         ht.Add("E098", "Amit");
         ht.Add("E110", "Jack");

         ICollection key = ht.Keys;

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

輸出

E001: Tom
E098: Amit
E110: Jack

Dictionary

Dictionary 是 C# 中的鍵值集合。Dictionary<TKey, TValue> 包含在 System.Collection.Generics 名稱空間中。

示例

 即時演示

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {

      IDictionary<int, int> dict = new Dictionary<int, int>();
      dict.Add(1,234);
      dict.Add(2,489);
      dict.Add(3,599);
      dict.Add(4,798);
      dict.Add(5,810);
      dict.Add(6,897);
      dict.Add(7,909);

      Console.WriteLine("Dictionary elements: "+dict.Count);
   }
}

輸出

Dictionary elements: 7

更新於: 22-Jun-2020

527 次觀看

開啟你的職業生涯

完成課程獲得認證

立即開始
廣告