คลาส Hashtable แสดงคอลเลกชันของคู่คีย์-ค่า (key-value pairs) จัดเรียงตามรหัสแฮชของคีย์ ใช้คีย์เข้าถึงสมาชิกในคอลเลกชัน
เมธอดที่ใช้บ่อย
| ลำดับ | เมธอดและคำอธิบาย |
|---|---|
| 1 | Add(object key, object value) เพิ่มสมาชิกพร้อมคีย์และค่าที่ระบุ |
| 2 | Clear() ลบสมาชิกทั้งหมด |
| 3 | ContainsKey(object key) ตรวจสอบว่ามีคีย์เฉพาะหรือไม่ |
| 4 | ContainsValue(object value) ตรวจสอบว่ามีค่าเฉพาะหรือไม่ |
ตัวอย่าง
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("D01", "Finance"); ht.Add("D02", "HR"); ht.Add("D03", "Operations");
if (ht.ContainsValue("Marketing"))
Console.WriteLine("This department name is already in the list");
else
ht.Add("D04", "Marketing");
ICollection key = ht.Keys;
foreach (string k in key) Console.WriteLine(k + ": " + ht[k]);
Console.ReadKey();
}
}
}
ใช้ Add() เพื่อเพิ่มคู่คีย์-ค่า:
Hashtable ht = new Hashtable(); ht.Add("D01", "Finance"); ht.Add("D02", "HR"); ht.Add("DO3", "Operations");
ผลลัพธ์
D04: Marketing D02: HR D03: Operations D01: Finance