- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策制定
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
- C# 高階教程
- C# - 屬性
- C# - 反射
- C# - 屬性
- C# - 索引器
- C# - 委託
- C# - 事件
- C# - 集合
- C# - 泛型
- C# - 匿名方法
- C# - 不安全程式碼
- C# - 多執行緒
- C# 有用資源
- C# - 問題和解答
- C# - 快速指南
- C# - 有用資源
- C# - 討論
C# - SortedList 類
SortedList 類表示一個鍵值對的集合,這些鍵值對按鍵排序,並且可以透過鍵和索引訪問。
排序列表是陣列和雜湊表的一個組合。它包含一個專案列表,可以使用鍵或索引訪問。如果使用索引訪問專案,則為 ArrayList,如果使用鍵訪問專案,則為 Hashtable。專案的集合始終按鍵值排序。
SortedList 類的屬性和方法
下表列出了 SortedList 類的一些常用屬性:
| 序號 | 屬性及描述 |
|---|---|
| 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");
}
// get a collection of the keys.
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