VB.Net - 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 Overridable Sub Add (key As Object, value As Object)

將具有指定鍵和值的元素新增到 SortedList 中。

2

Public Overridable Sub Clear

從 SortedList 中刪除所有元素。

3

Public Overridable Function ContainsKey (key As Object) As Boolean

確定 SortedList 是否包含特定鍵。

4

Public Overridable Function ContainsValue (value As Object) As Boolean

確定 SortedList 是否包含特定值。

5

Public Overridable Function GetByIndex (index As Integer) As Object

獲取 SortedList 中指定索引處的值。

6

Public Overridable Function GetKey (index As Integer) As Object

獲取 SortedList 中指定索引處的鍵。

7

Public Overridable Function GetKeyList As IList

獲取 SortedList 中的鍵。

8

Public Overridable Function GetValueList As IList

獲取 SortedList 中的值。

9

Public Overridable Function IndexOfKey (key As Object) As Integer

返回 SortedList 中指定鍵的基於零的索引。

10

Public Overridable Function IndexOfValue (value As Object ) As Integer

返回 SortedList 中指定值的第一次出現的基於零的索引。

11

Public Overridable Sub Remove (key As Object)

從 SortedList 中刪除具有指定鍵的元素。

12

Public Overridable Sub RemoveAt (index As Integer)

刪除 SortedList 中指定索引處的元素。

13

Public Overridable Sub TrimToSize

將容量設定為 SortedList 中的實際元素數。

示例

以下示例演示了該概念 -

Module collections
   Sub Main()
      Dim sl As SortedList = 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")) Then
         Console.WriteLine("This student name is already in the list")
      Else
         sl.Add("008", "Nuha Ali")
      End If
       ' Get a collection of the keys. 
      Dim key As ICollection = sl.Keys
      Dim k As String
      
      For Each k In key
         Console.WriteLine(" {0} : {1}", k, sl(k))
      Next k
      Console.ReadKey()
   End Sub
End Module

當以上程式碼編譯並執行時,它會產生以下結果 -

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

© . All rights reserved.