1. 创建 SortedList: 若要使用 SortedList,首先需要在代码中实例化它。你可以使用 new 关键字创建一个新的 SortedList 对象。
using System.Collections;
// ...
SortedList mySortedList = new SortedList();
2. 添加键/值对: 使用 Add 方法将键和相应的值添加到 SortedList 中。SortedList 会自动根据键的顺序进行排序。
mySortedList.Add("Key1", "Value1");
mySortedList.Add("Key3", 42);
mySortedList.Add("Key2", new CustomObject());
3. 访问值: 通过键来访问 SortedList 中的值。由于 SortedList 是有序的,你可以按顺序访问元素。
object value = mySortedList["Key1"];
4. 删除键/值对: 使用 Remove 方法通过键来删除键/值对。
mySortedList.Remove("Key3");
5. 包含键: 使用 ContainsKey 方法检查 SortedList 是否包含指定的键。
bool containsKey = mySortedList.ContainsKey("Key2");
6. 遍历键/值对: 使用 foreach 循环遍历 SortedList 中的所有键/值对。由于 SortedList 是有序的,你可以按顺序处理元素。
foreach (DictionaryEntry entry in mySortedList)
{
// entry.Key 和 entry.Value 分别是键和值
// 处理每个键/值对的逻辑
}
7. Count 属性: SortedList 提供 Count 属性,用于获取集合中键/值对的数量。
int numberOfItems = mySortedList.Count;
SortedList 是一种在需要有序键/值对集合时很有用的数据结构。请注意,与 Hashtable 相比,SortedList 的操作可能稍慢,因为它需要维护有序状态。如果只需哈希表而不需要排序,Hashtable 可能更适合。在较新版本的 .NET 中,你也可以考虑使用泛型的 SortedDictionary<TKey, TValue> 或 Dictionary<TKey, TValue>,以获得更好的类型安全性和性能。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6581/ASP.NET