VB.Net SortedList类

SortedList类代表按键排序的键值对集合,可通过键和索引进行访问。

排序列表(SortedList)是数组和散列表的组合。它包含可以使用键或索引访问的项目列表。如果使用索引访问项目,则它是一个ArrayList,如果使用键访问项目,则它是一个Hashtable。 项目的集合总是按键值排序。

SortedList类的属性和方法

下表列出了SortedList类的一些常用属性:

编号 属性 描述
1 Capacity 获取或设置Hashtable可以包含的元素的数量。
2 Count 获取SortedList中包含的元素的数量。
3 IsFixedSize 获取一个值,该值指示Hashtable是否具有固定的大小。
4 IsReadOnly 获取一个值,该值指示Hashtable是否是只读的。
5 Item 获取或设置指定键关联的元素。
6 Keys 获取包含Hashtable中的键的ICollection
7 Values 获取包含Hashtable中的值的ICollection

下表列出了SortedList类的一些常用方法:

编号 方法 描述
1 Public Overridable Sub Add (key As Object, value As Object)
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中元素的实际数量。

示例

以下示例演示了这个概念:

Imports System.Collections

Module modhashtable
   Sub Main()
      Dim ht As Hashtable = New Hashtable()
      Dim k As String
      ht.Add("001", "Haikou Lee")
      ht.Add("002", "Abida Rehman")
      ht.Add("003", "Joe Holzner")
      ht.Add("004", "Mausam Benazir Nur")
      ht.Add("005", "M. Amlan")
      ht.Add("006", "M. Arif")
      ht.Add("007", "Ritesh Wong")
      If (ht.ContainsValue("Nuha Ali")) Then
          Console.WriteLine("This student name is already in the list")
      Else
          ht.Add("008", "Nuha Lee")
      End If
      ' Get a collection of the keys. 
      Dim key As ICollection = ht.Keys
      For Each k In key
          Console.WriteLine(" {0} : {1}", k, ht(k))
      Next k
      Console.ReadKey()
   End Sub
End Module

执行上面示例代码,得到以下结果 -

F:\worksp\vb.net\collection>vbc MySortedList.vb
F:\worksp\vb.net\collection>MySortedList.exe
 001 : Hakou lee
 002 : Abida Rehman
 003 : Joe Holzner
 004 : Mausam Benazir Nur
 005 : M. Amlan
 006 : M. Arif
 007 : Ritesh Wong
 008 : Nuha Ali

上一篇: VB.Net集合 下一篇: VB.Net函数