基本概念
Hashtable 位於 System.Collections,以 key/value 鍵值對儲存資料,key 區分大小寫、不可重複,key/value 均為 object 型別,可存放任意型別資料。
常用操作
| 操作 | 方法/屬性 | 說明 |
| 新增 | Add(key, value) | key 重複會拋出例外 |
| 移除單筆 | Remove(key) | |
| 清空 | Clear() | |
| 判斷 key 存在 | Contains(key) / ContainsKey(key) | 回傳 bool |
| 存取值 | ht[key] (索引子) | key 不存在回傳 null |
| 取得所有 key | ht.Keys | 回傳 ICollection |
| 取得所有 value | ht.Values | 回傳 ICollection |
完整範例
using System;
using System.Collections;
class Demo
{
static void Main()
{
Hashtable ht = new Hashtable();
ht.Add("E", "e");
ht.Add("A", "a");
ht.Add("C", "c");
ht.Add("B", "b");
Console.WriteLine(ht["A"]); // a
Console.WriteLine(ht.Contains("E")); // True
ht.Remove("C");
ht.Clear();
Console.WriteLine(ht["A"]); // null
}
}
遍歷哈希表
foreach (DictionaryEntry de in ht)
{
Console.WriteLine($"Key: {de.Key}, Value: {de.Value}");
}
排序輸出 (Hashtable 本身不保證順序)
ArrayList keys = new ArrayList(ht.Keys);
keys.Sort(); // 依字母排序
foreach (string k in keys)
Console.WriteLine($"{k}: {ht[k]}");
替代方案:SortedList / Dictionary<TKey, TValue>
- SortedList:內部依 key 自動排序,效能較 Hashtable 低,適合資料量小且需順序的場景。
- Dictionary<TKey, TValue> (Generic):型別安全、效能優於 Hashtable,**推薦新專案優先使用**。
var dict = new Dictionary { {"c",41}, {"a",42}, {"d",11}, {"b",13} };
foreach (var kv in dict.OrderBy(k => k.Key))
Console.WriteLine($"{kv.Key}: {kv.Value}");
效能與選擇建議
| 集合 | 型別安全 | 排序 | 效能 | 適用場景 |
| Hashtable | 否 | 無序 | 中 | 舊版相容、非泛型需求 |
| SortedList | 否 | Key 排序 | 低 (插入 O(n)) | 小量資料需排序 |
| Dictionary<TKey,TValue> | 是 | 無序 | 高 | **一般首選** |
| SortedDictionary<TKey,TValue> | 是 | Key 排序 | 中 (O(log n)) | 需排序且型別安全 |