SortedList類表示按鍵排序的鍵值對的集合,可以通過鍵和索引訪問。
排序列表是數組和散列表的組合。 它包含可以使用鍵或索引訪問的專案列表。 如果您使用索引訪問專案,它是一個ArrayList,如果使用鍵訪問專案,它是一個Hashtable。專案的集合總是按鍵值排序。
SortedList類的方法和屬性
下表列出了SortedList類的一些常用屬性:
| 屬性 | 描述 |
|---|---|
| Capacity | 獲取或設置SortedList的容量。 |
| Count | 獲取SortedList中包含的元素數量。 |
| IsFixedSize | 獲取一個值,指示SortedList是否具有固定大小。 |
| IsReadOnly | 獲取一個值,指示SortedList是否為只讀。 |
| Item | 獲取並設置與SortedList中的指定鍵相關聯的值。 |
| Keys | 獲取SortedList中的鍵。 |
| 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", "Maxsu");
sl.Add("002", "Alibaba");
sl.Add("003", "Tencent");
sl.Add("004", "Google");
sl.Add("005", "Microsoft");
sl.Add("006", "Apple");
sl.Add("007", "Huawei");
if (sl.ContainsValue("zaixian"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
sl.Add("008", "zaixian");
}
// get a collection of the keys.
ICollection key = sl.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
}
}
}
當上述代碼被編譯並執行時,它產生以下結果:
001: Maxsu
002: Alibaba
003: Tencent
004: Google
005: Microsoft
006: Apple
007: Huawei
008: zaixian
