VB.Net 教程:SortedList

返回到:VB.Net – 集合

SortedList类表示按键排序并可通过键和索引访问的键 – 值对的集合。

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

SortedList类的属性和方法

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

属性描述
Capacity获取或设置SortedList的容量。
Count获取SortedList中包含的元素数。
IsFixedSize获取指示SortedList是否具有固定大小的值。
IsReadOnly获取指示SortedList是否为只读的值。
Item获取并设置与SortedList中的特定键相关联的值。
Key获取SortedList中的键。
Values获取SortedList中的值。

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

S.N方法名称和用途
1Public Overridable Sub Add (key As Object, value As Object)将带有指定的键和值的元素添加到可排序列表。
2Public Overridable Sub Clear从SortedList中删除所有元素。
3Public Overridable Function ContainsKey (key As Object) As Boolean确定SortedList是否包含特定键。
4Public Overridable Function ContainsValue (value As Object) As Boolean确定SortedList是否包含特定值。
5Public Overridable Function GetByIndex (index As Integer) As Object获取SortedList的指定索引处的值。
6Public Overridable Function GetKey (index As Integer) As Object获取SortedList的指定索引处的键。
7Public Overridable Function GetKeyList As IList获取SortedList中的键。
8Public Overridable Function GetValueList As IList获取SortedList中的值。
9Public Overridable Function IndexOfKey (key As Object) As Integer返回SortedList中指定键的从零开始的索引。
10Public Overridable Function IndexOfValue (value As Object ) As Integer返回SortedList中指定值的第一次出现的从零开始的索引。
11Public Overridable Sub Remove (key As Object)从SortedList中删除具有指定键的元素。
12Public Overridable Sub RemoveAt (index As Integer)删除SortedList的指定索引处的元素。
13Public 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 – 集合

作者:terry,如若转载,请注明出处:https://www.web176.com/vbnet_api/11483.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年3月1日
下一篇 2023年3月1日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注