foreach (DictionaryEntry de in ht) {
Console.WriteLine($"Key: {de.Key}, Value: {de.Value}");
}
ArrayList keys = new ArrayList(ht.Keys);
keys.Sort(); // 字母順序
foreach (string key in keys) {
Console.WriteLine($"{key}: {ht[key]}");
}
SortedList 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 (依 Key 排序)
| 特性 | Hashtable | SortedList |
|---|---|---|
| Key 排序 | 無序 | 自動排序 |
| 查找效能 | O(1) | O(log n) |
| 記憶體 | 較小 | 較大(維護兩個陣列) |
需頻繁排序輸出時用 SortedList;純查找高效能用 Hashtable。