C# - SortedList 类
SortedList 类表示一个键值对的集合,这些键值对按键排序,并可通过按键和索引访问。
排序列表是数组和哈希表的组合。它包含一个可以使用键或索引访问的项目列表。如果使用索引访问项目,则它是一个 ArrayList;如果使用键访问项目,则它是一个 Hashtable。项目集合始终按键值排序。
SortedList 类的方法和属性
下表列出了 SortedList 类的一些常用属性 -
| Sr.No. | 属性 &描述 |
|---|---|
| 1 | Capacity 获取或设置 SortedList 的容量。 |
| 2 | Count 获取 SortedList 中包含的元素数量。 |
| 3 | IsFixedSize 获取一个值,指示 SortedList 是否具有固定大小。 |
| 4 | IsReadOnly 获取一个值,指示SortedList 是只读的。 |
| 5 | Item 获取并设置 SortedList 中特定键关联的值。 |
| 6 | Keys 获取 SortedList 中的键。 |
| 7 | Values 获取 SortedList 中的值。 |
下表列出了 SortedList 类的一些常用方法 -
| 序号 | 方法及说明 |
|---|---|
| 1 | public virtual void Add(object key, object value); 将具有指定键和值的元素添加到 SortedList 中。 |
| 2 | public virtual void Clear(); 从 SortedList 中移除所有元素。 |
| 3 | public virtual bool ContainsKey(object key); 判断 SortedList 是否包含特定键。 |
| 4 | public virtual bool ContainsValue(object value); 判断 SortedList 是否包含特定值。 |
| 5 | public virtual object GetByIndex(int index); 获取 SortedList 中指定索引处的值。 |
| 6 | public virtual object GetKey(int index); 获取 SortedList 中指定索引处的键。 |
| 7 | public virtual IList GetKeyList(); 获取 SortedList 中的键。 |
| 8 | public virtual IList GetValueList(); 获取 SortedList 中的值。 |
| 9 | public virtual int IndexOfKey(object key); 返回 SortedList 中指定键的从零开始的索引。 |
| 10 | public virtual int IndexOfValue(object value); 返回 SortedList 中指定值第一次出现的从零开始的索引。 |
| 11 | public virtual void Remove(object key); 删除元素使用 SortedList 中指定的键。 |
| 12 | public virtual void RemoveAt(int index); 删除 SortedList 中指定索引处的元素。 |
| 13 | public virtual void TrimToSize(); 将容量设置为 SortedList 中元素的实际数量。 |
示例
以下示例演示了以下概念:
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
SortedList sl = new SortedList();
sl.Add("001", "Zara Ali");
sl.Add("002", "Abida Rehman");
sl.Add("003", "Joe Holzner");
sl.Add("004", "Mausam Benazir Nur");
sl.Add("005", "M. Amlan");
sl.Add("006", "M. Arif");
sl.Add("007", "Ritesh Saikia");
if (sl.ContainsValue("Nuha Ali")) {
Console.WriteLine("This student name is already in the list");
} else {
sl.Add("008", "Nuha Ali");
}
// 获取 key 键的集合。
ICollection key = sl.Keys;
foreach (string k in key) {
Console.WriteLine(k + ": " + sl[k]);
}
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
001: Zara Ali 002: Abida Rehman 003: Joe Holzner 004: Mausam Banazir Nur 005: M. Amlan 006: M. Arif 007: Ritesh Saikia 008: Nuha Ali

csharp_collections.html