Hashtable 是經典非泛型鍵值對集合,以雜湊表實作提供 **O(1) 平均查找/插入/刪除效能**,適合不需排序、強調查找速度的選單資料來源。本文涵蓋 Hashtable 建立、繫結、與 SortedList 差異比較、現代泛型替代方案。
System.CollectionsAdd(key, value) 新增項目Hashtable.Synchronized() 取得同步包裝器<script runat="server">
void Page_Load() {
if (!IsPostBack) {
Hashtable countries = new Hashtable();
countries.Add("TW", "台灣");
countries.Add("JP", "日本");
countries.Add("US", "美國");
countries.Add("CN", "中國");
rblCountries.DataSource = countries;
rblCountries.DataTextField = "Value";
rblCountries.DataValueField = "Key";
rblCountries.DataBind();
}
}
void rblCountries_SelectedIndexChanged(object sender, EventArgs e) {
lblResult.Text = "選擇:" + rblCountries.SelectedItem.Text + " (" + rblCountries.SelectedValue + ")";
}
</script>
<html><body>
<form runat="server">
<h3>國家代碼選單(Hashtable,順序不固定):</h3>
<asp:RadioButtonList ID="rblCountries" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="rblCountries_SelectedIndexChanged">
</asp:RadioButtonList>
<br /><br />
<asp:Label ID="lblResult" runat="server" ForeColor="Blue" Font-Bold="true" />
</form>
</body></html>
Hashtable ht = new Hashtable();
ht["Key1"] = "Value1"; // 新增/修改(索引器語法)
ht.Add("Key2", "Value2"); // 新增(Key 重複拋例外)
string val = (string)ht["Key1"]; // 讀取(需型別轉換)
bool exists = ht.ContainsKey("Key1"); // true
bool hasVal = ht.ContainsValue("Value1"); // true
ht.Remove("Key1"); // 移除指定 Key
ht.Clear(); // 清空
// 方式 1:DictionaryEntry 列舉
foreach (DictionaryEntry entry in ht) {
Response.Write(entry.Key + "=" + entry.Value + "<br/>");
}
// 方式 2:Keys 集合
foreach (string key in ht.Keys) {
Response.Write(key + "=" + ht[key] + "<br/>");
}
// 方式 3:Values 集合
foreach (string val in ht.Values) {
Response.Write(val + "<br/>");
}
Hashtable clone = (Hashtable)ht.Clone(); // 淺層複製
Hashtable sync = Hashtable.Synchronized(ht); // 執行緒安全包裝
| 維度 | Hashtable | SortedList | Dictionary<TKey,TValue> |
|---|---|---|---|
| 順序保證 | 無(雜湊分佈) | 自動排序(依 Key) | 無(插入順序 .NET 3.7+ 保持) |
| 查找效能 | O(1) 平均 | O(log n) 二分搜尋 | O(1) 平均 |
| 插入效能 | O(1) 平均 | O(n) 陣列位移 | O(1) 平均 |
| 型別安全 | 否(object) | 否(object) | 是(泛型) |
| Null Key | 不允許 | 不允許 | 允許 |
| Null Value | 允許 | 允許 | 允許 |
| 索引存取 | 不支援 | 支援 GetByIndex/SetByIndex | 不支援 |
| 記憶體開銷 | 中等 | 較低(陣列) | 中等 |
| 執行緒安全 | 靜態 Synchronized() | 無內建 | 無內建 |
<asp:DropDownList ID="ddlCountries" runat="server"
DataSourceID="htCountries"
DataTextField="Value" <-- 顯示 Hashtable 的 Value
DataValueField="Key" <-- 實際值為 Hashtable 的 Key
/>
適用控制項:RadioButtonList、CheckBoxList、DropDownList、ListBox、BulletedList
注意:Hashtable **無法指定項目排序順序**。若需要字母或數字排序,請改用
SortedList、SortedDictionary或泛型List<T>+ LINQOrderBy。
.NET 2.0+ 強烈建議使用泛型 Dictionary<string, string>:
<script runat="server">
void Page_Load() {
if (!IsPostBack) {
var countries = new Dictionary<string, string> {
{"TW", "台灣"}, {"JP", "日本"}, {"US", "美國"}, {"CN", "中國"}
};
// 若需排序:countries.OrderBy(kvp => kvp.Key).ToList()
// 若需保持插入順序:.NET 4.7+ Dictionary 保持插入順序
rblCountries.DataSource = countries;
rblCountries.DataTextField = "Value";
rblCountries.DataValueField = "Key";
rblCountries.DataBind();
}
}
</script>
Where、OrderBy、Select 等查詢| 需求 | 推薦集合 | 理由 |
|---|---|---|
| 高頻查找、不需排序、舊版相容 | Hashtable | O(1) 查找、.NET 1.0 即支援 |
| 高頻查找、不需排序、新專案 | Dictionary<TKey,TValue> | 型別安全、效能最佳、現代標準 |
| 需自動排序、小量資料 | SortedList | 陣列實作、記憶體效率高、支援索引 |
| 需自動排序、大量資料、頻繁插入 | SortedDictionary<TKey,TValue> | 紅黑樹實作、O(log n) 插入/查找 |
| 需保持插入順序、快速查找 | Dictionary (.NET 4.7+) | 插入順序 = 列舉順序 |
ht[key] = value 會靜默覆蓋,Add 會拋 ArgumentException(string)ht[key] 若實際型別不符會拋 InvalidCastException,建議 ht[key]?.ToString()Hashtable 以雜湊表高效查找特性服務於非排序選單場景,但現代開發首選型別安全的 Dictionary<TKey,TValue>。下一節將介紹 ArrayList 集合繫結與排序操作。