蓝色天空.知识 · 实践 · 创造
我的收藏
Web Forms 教程目录 55章
Web Forms / LEARN BY DOING

WebForms SortedList

讲解 ASP.NET WebForms 中兼具 ArrayList 与 Hashtable 优势的 SortedList 集合:自动按键排序、TrimToSize 容量收敛、列表控件绑定与事件响应及现代泛型演进。

学完这一章,你能够

  • 讲解 ASP.NET WebForms 中兼具 ArrayList 与 Hashtable 优势的 SortedList 集合:自动按键排序、TrimToSize 容量收敛、列表控件绑定与事件响应及现代泛型演进。

SortedList 的特性与自动排序机制

`SortedList` 对象结合了 `ArrayList`(可按索引访问、支持容量裁剪)与 `Hashtable`(按键/值对存储与检索)两者的特性,常用于需要确定排列顺序的 `RadioButtonList` 与 `DropDownList` 数据绑定场景。

`SortedList` 内部维护有序键值对:每当调用 `Add(key, value)` 插入条目时,集合都会自动按照键的字母顺序或数字顺序重新定位,同时也可调用 `TrimToSize()` 将内部数组容量收缩至实际元素数量。例如依次插入 `("N", "Norway")`、`("S", "Sweden")`、`("F", "France")`、`("I", "Italy")` 后,集合会自动按 `F -> I -> N -> S` 排好顺序。

绑定 SortedList 到列表控件与交互事件

`SortedList` 同样可为 `asp:RadioButtonList`、`asp:CheckBoxList`、`asp:DropDownList` 与 `asp:ListBox` 自动生成选项。只需在 `.aspx` 页面声明不带静态 `<asp:ListItem>` 的 `<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />`,并在 `Page_Load` 的首次加载判断中配置 `rb.DataSource = mycountries`、`rb.DataValueField = "Key"`、`rb.DataTextField = "Value"` 与 `rb.DataBind()`,即可渲染出严格按字母升序排列的单选按钮组。

进一步添加 `OnSelectedIndexChanged="displayMessage"` 事件处理器后,当用户点击单选按钮时,服务端把 `"Your favorite country is: " & rb.SelectedItem.Text` 输出到 `lbl1`。本站离线实验核验了字符键自动排序与 `TrimToSize()`、双控件确定顺序渲染、选中首项 `F` 触发事件以及数字键按大小排序兼按索引/按键双模式读取。在现代 .NET / ASP.NET Core 中,应优先采用泛型 `SortedList<TKey, TValue>` 或配合 LINQ `OrderBy` 对强类型集合排序。

离线校验 SortedList 自动排序、TrimToSize、列表控件绑定与数字键双访问模式

含完整源码 · 143 行
展开查看收起
python
"""Offline ASP.NET WebForms verifier for Chapter 48 (sortedlist)."""
from __future__ import annotations

import bisect
import json

VERSION = "CPython 3.12.14 offline ASP.NET WebForms verifier (IIS/ASP.NET runtime absent)"


class DotNetSortedList:
    """Minimal model of System.Collections.SortedList (auto-sorted by key, indexable)."""

    def __init__(self, initial_capacity: int = 16) -> None:
        self._keys: list = []
        self._values: list = []
        self.capacity: int = initial_capacity

    def add(self, key, value) -> None:
        idx = bisect.bisect_left(self._keys, key)
        if idx < len(self._keys) and self._keys[idx] == key:
            raise KeyError(f"Duplicate key in SortedList: {key}")
        if len(self._keys) >= self.capacity:
            self.capacity = max(4, self.capacity * 2)
        self._keys.insert(idx, key)
        self._values.insert(idx, value)

    def trim_to_size(self) -> None:
        self.capacity = len(self._keys)

    def get_by_index(self, index: int):
        return self._values[index]

    def get_by_key(self, key):
        idx = bisect.bisect_left(self._keys, key)
        if idx < len(self._keys) and self._keys[idx] == key:
            return self._values[idx]
        raise KeyError(key)

    def entries(self) -> list[dict[str, object]]:
        return [{"Key": k, "Value": v} for k, v in zip(self._keys, self._values)]


def main() -> None:
    sl = DotNetSortedList(initial_capacity=16)
    sl.add("N", "Norway")
    sl.add("S", "Sweden")
    sl.add("F", "France")
    sl.add("I", "Italy")
    cap_before = sl.capacity
    sl.trim_to_size()
    cap_after = sl.capacity

    ordered_pairs = [(e["Key"], e["Value"]) for e in sl.entries()]
    radio_items = [{"value": e["Key"], "text": e["Value"]} for e in sl.entries()]
    dropdown_items = list(radio_items)

    # Case 3: Select index 0 ("F" -> "France") triggering displayMessage
    selected = radio_items[0]
    lbl1_text = f"Your favorite country is: {selected['text']}"

    # Case 4: Numeric keys auto-sort + dual key/index access + duplicate key rejection
    num_sl = DotNetSortedList()
    num_sl.add(30, "Thirty")
    num_sl.add(10, "Ten")
    num_sl.add(20, "Twenty")
    dup_error = False
    try:
        num_sl.add(20, "Duplicate")
    except KeyError:
        dup_error = True

    cases = [
        {
            "name": "sortedlist_auto_sort_and_trim",
            "summary": "验证 SortedList 插入 N/S/F/I 后自动按键字母升序排列,且 TrimToSize() 将容量从 16 收缩为 4",
            "expected": {
                "ordered": [("F", "France"), ("I", "Italy"), ("N", "Norway"), ("S", "Sweden")],
                "cap_before": 16,
                "cap_after": 4,
            },
            "actual": {
                "ordered": ordered_pairs,
                "cap_before": cap_before,
                "cap_after": cap_after,
            },
            "passed": (
                ordered_pairs == [("F", "France"), ("I", "Italy"), ("N", "Norway"), ("S", "Sweden")]
                and cap_before == 16
                and cap_after == 4
            ),
        },
        {
            "name": "sortedlist_bind_dropdown_and_radio",
            "summary": "验证绑定至 RadioButtonList 与 DropDownList 后选项严格按 F -> I -> N -> S 顺序渲染",
            "expected": {
                "radio_keys": ["F", "I", "N", "S"],
                "dropdown_texts": ["France", "Italy", "Norway", "Sweden"],
            },
            "actual": {
                "radio_keys": [x["value"] for x in radio_items],
                "dropdown_texts": [x["text"] for x in dropdown_items],
            },
            "passed": (
                [x["value"] for x in radio_items] == ["F", "I", "N", "S"]
                and [x["text"] for x in dropdown_items] == ["France", "Italy", "Norway", "Sweden"]
            ),
        },
        {
            "name": "sortedlist_selected_index_changed",
            "summary": "模拟选中排序后首项 F(France)并触发 displayMessage 输出标签文本",
            "expected": "Your favorite country is: France",
            "actual": lbl1_text,
            "passed": lbl1_text == "Your favorite country is: France",
        },
        {
            "name": "sortedlist_numeric_key_and_index",
            "summary": "验证 SortedList 兼具数字键自动排序、按键查询、按索引读取及重复键冲突检测",
            "expected": {
                "sorted_numeric_keys": [10, 20, 30],
                "by_index_1": "Twenty",
                "by_key_30": "Thirty",
                "duplicate_rejected": True,
            },
            "actual": {
                "sorted_numeric_keys": [e["Key"] for e in num_sl.entries()],
                "by_index_1": num_sl.get_by_index(1),
                "by_key_30": num_sl.get_by_key(30),
                "duplicate_rejected": dup_error,
            },
            "passed": (
                [e["Key"] for e in num_sl.entries()] == [10, 20, 30]
                and num_sl.get_by_index(1) == "Twenty"
                and num_sl.get_by_key(30) == "Thirty"
                and dup_error is True
            ),
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对 N/S/F/I 自动排序为 F/I/N/S 且容量由 16 缩至 4、Radio/DropDown 确定顺序、displayMessage 响应及数字键索引/键查询。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2981.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Web Forms

课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2981.zip

下载课程关联工程包:Web Forms

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2976.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

当界面要求选项按字母或数字顺序稳定展示、或需要同时按键与按整数下标访问条目时,应选用 `SortedList`;若只关心 O(1) 按键查找且不关心遍历顺序,则可选 `Hashtable`(现代项目改用 `Dictionary<TKey, TValue>` 或 `SortedList<TKey, TValue>`)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习