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
csharp_collections.htm
廣告

© . All rights reserved.