Hashtable
คลาส Hashtable แสดงถึงคอลเลกชันของคู่คีย์-ค่า (key-value pairs) ที่จัดระเบียบตามรหัสแฮชของคีย์ ใช้คีย์ในการเข้าถึงสมาชิกในคอลเลกชัน
เมธอดที่ใช้บ่อยใน Hashtable:
| No. | Method & Description |
|---|---|
| 1 | Add(object key, object value) เพิ่มสมาชิกพร้อมคีย์และค่าที่ระบุ |
| 2 | Clear() ลบสมาชิกทั้งหมดออกจาก Hashtable |
| 3 | ContainsKey(object key) ตรวจสอบว่า Hashtable มีคีย์เฉพาะเจาะจงหรือไม่ |
| 4 | ContainsValue(object value) ตรวจสอบว่า Hashtable มีค่าเฉพาะเจาะจงหรือไม่ |
ตัวอย่าง Hashtable
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();
}
}
}
ผลลัพธ์
D04: Marketing D02: HR D03: Operations D01: Finance
Dictionary
Dictionary<TKey, TValue> เป็นคอลเลกชันของคีย์และค่าใน C# อยู่ในเนมสเปซ System.Collections.Generic
เมธอดหลัก:
| No. | Methods & Description |
|---|---|
| 1 | Add - เพิ่มคู่คีย์-ค่า |
| 2 | Clear() - ลบคีย์และค่าทั้งหมด |
| 3 | Remove - ลบสมาชิกด้วยคีย์ที่ระบุ |
| 4 | ContainsKey - ตรวจสอบคีย์ที่มีอยู่ |
| 5 | ContainsValue - ตรวจสอบค่าที่มีอยู่ |
| 6 | Count - นับจำนวนคู่คีย์-ค่า |
ตัวอย่าง Dictionary
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1, 44);
d.Add(2, 34);
d.Add(3, 66);
d.Add(4, 47);
d.Add(5, 76);
Console.WriteLine(d.Count);
}
}
ผลลัพธ์
5