在 ASP.NET MVC 中,与 WebForms 中的 SortedList 相对应的是 SortedDictionary<TKey, TValue> 类。SortedList 是一个非泛型的集合,而 SortedDictionary<TKey, TValue> 是一个泛型集合,它提供了更好的类型安全性,并且在遍历时保持按键排序。

下面是一个简单的例子,演示如何在 ASP.NET MVC 中使用 SortedDictionary<TKey, TValue>:
// 在控制器中定义一个 SortedDictionary<TKey, TValue>
public class MyController : Controller
{
    public ActionResult Index()
    {
        SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();
        mySortedDictionary.Add(3, "Item 3");
        mySortedDictionary.Add(1, "Item 1");
        mySortedDictionary.Add(2, "Item 2");

        return View(mySortedDictionary);
    }
}

然后,您可以在视图中迭代这个排序字典,并显示其中的键值对:
@model SortedDictionary<int, string>

<h2>Items Sorted Dictionary</h2>

<ul>
    @foreach (var pair in Model)
    {
        <li>Key: @pair.Key, Value: @pair.Value</li>
    }
</ul>

在上述例子中,SortedDictionary<int, string> 用于存储整数键和字符串值的键值对,按键排序。在控制器的动作方法中初始化并传递给视图。在视图中,使用 @model 指令指定模型类型,然后使用 foreach 循环遍历排序字典并显示每个键值对的信息。

类似地,如果您需要处理更复杂的数据结构,可以创建自定义的模型类,并使用 SortedDictionary<TKey, TValue> 存储该类的实例。这样,您可以更灵活地表示和操作数据。


转载请注明出处:http://www.pingtaimeng.com/article/detail/14940/ASP.NET MVC