Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่างพจนานุกรมและ Hashtable ใน C #


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

พจนานุกรม

พจนานุกรมคือชุดของคีย์และค่าใน C # Dictionary รวมอยู่ในเนมสเปซ 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