鍵值對集合,類似字典但更強大。經過優化,任意型別鍵值存取速度優於其他集合。
var myHT = new Hashtable();
myHT.Add("one", "The");
myHT.Add("two", "quick");
myHT.Add("three", "brown");
myHT.Add("four", "fox");
foreach (string key in myHT.Keys)
Console.WriteLine(key);
foreach (DictionaryEntry de in myHT)
Console.WriteLine($" {de.Key}: {de.Value}");
核心機制:GetHashCode() 產生整數雜湊碼,決定儲存位置。
類似 Hashtable,但鍵值陣列已排序。
var sl = new SortedList();
sl["c"] = 41;
sl["a"] = 42;
sl["d"] = 11;
sl["b"] = 13;
foreach (DictionaryEntry de in sl)
Console.WriteLine($"{de.Key},{de.Value}");
// 輸出按鍵排序:a,42 / b,13 / c,41 / d,11
位於 System.Collections.Specialized,屬特殊集合。
HybridDictionary:< 10 元素用此,增多自動轉 HashtableStringCollection:字串專用集合Hashtable 鍵唯一,NameValueCollection 鍵可重複:
var ht = new Hashtable();
ht.Add("key", "value1");
ht.Add("key", "value2"); // 拋出異常
var nvc = new NameValueCollection();
nvc.Add("key", "value1");
nvc.Add("key", "value2"); // 允許,儲存多值
// nvc["key"] 回傳 "value1,value2"
| 集合 | 特點 | 適用場景 |
|---|---|---|
| Hashtable | 快速查找、鍵唯一 | 一般鍵值對儲存 |
| SortedList | 鍵自動排序 | 需有序遍歷 |
| NameValueCollection | 鍵可重複、字串優化 | HTTP 標頭、查詢字串 |
| HybridDictionary | 小量元素優化 | 元素數量不確定 |