ภาพรวม
HybridDictionary ใน namespace System.Collections.Specialized เป็นดิกชันนารีแบบไฮบริดที่สลับระหว่าง ListDictionary (สำหรับข้อมูลน้อย) และ Hashtable (สำหรับข้อมูลมาก) อัตโนมัติ รองรับการเข้าถึงค่าโดยใช้คีย์ผ่านดัชนี (indexer)
ตัวอย่างที่ 1: ดึงค่าด้วยคีย์
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary myDict = new HybridDictionary();
myDict.Add("1", "Tablet");
myDict.Add("2", "Desktop");
myDict.Add("3", "Speakers");
myDict.Add("4", "Laptop");
myDict.Add("5", "Notebook");
myDict.Add("6", "Ultrabook");
myDict.Add("7", "HDD");
myDict.Add("8", "SDD");
Console.WriteLine("Value at key 5 = " + myDict["5"]);
}
}
ผลลัพธ์
Value at key 5 = Notebook
ตัวอย่างที่ 2: ดึงและอัปเดตค่า
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
HybridDictionary myDict = new HybridDictionary();
myDict.Add("1", "Tablet");
myDict.Add("2", "Desktop");
myDict.Add("3", "Speakers");
myDict.Add("4", "Laptop");
myDict.Add("5", "Notebook");
myDict.Add("6", "Ultrabook");
myDict.Add("7", "HDD");
myDict.Add("8", "SDD");
Console.WriteLine("Value at key 5 = " + myDict["5"]);
myDict["5"] = "Smart Watches";
Console.WriteLine("Value at key 5 [UPDATED] = " + myDict["5"]);
}
}
ผลลัพธ์
Value at key 5 = Notebook
Value at key 5 [UPDATED] = Smart Watches
ตัวอย่างที่ 3: การใช้งาน Queue (เนื้อหาเพิ่มเติมในต้นฉบับ)
โค้ดตัวอย่างที่ 3 ในต้นฉบับแสดงการใช้งาน Queue ซึ่งเป็นคลาสแยกต่างหาก ไม่เกี่ยวข้องกับ HybridDictionary จึงไม่ได้รวมไว้ในบทความนี้
คำอธิบายเพิ่มเติม
- การใช้ดัชนี
myDict[key]ทำหน้าที่ทั้ง get (ดึงค่า) และ set (ตั้งค่า/อัปเดตค่า) - หากคีย์ไม่มีอยู่ การ get จะคืนค่า
nullการ set จะเพิ่มคีย์ใหม่ - HybridDictionary เหมาะสำหรับสถานการณ์ที่จำนวนข้อมูลเปลี่ยนแปลงมาก และต้องการประสิทธิภาพดีทั้งขนาดเล็กและใหญ่