哈希表Hashtable类表示基于密钥的哈希码组织的键 - 值对的集合。 它使用键来访问集合中的元素。
当您需要使用键访问元素时使用散列表,您可以标识有用的键值。 散列表中的每个项都有一个键/值对。 该键用于访问集合中的项目。
Hashtable类的属性和方法
下表列出了Hashtable类的一些常用属性:
属性 | 描述 |
---|---|
Count | Gets the number of key-and-value pairs contained in the Hashtable. 获取Hashtable中包含的键 - 值对的数量。 |
IsFixedSize | Gets a value indicating whether the Hashtable has a fixed size. 获取指示散列表是否具有固定大小的值。 |
IsReadOnly | Gets a value indicating whether the Hashtable is read-only. 获取一个值,指示Hashtable是否为只读。 |
Item | Gets or sets the value associated with the specified key. 获取或设置与指定键相关联的值。 |
Keys | Gets an ICollection containing the keys in the Hashtable. 获取包含该Hashtable中的键的集合。 |
Values | Gets an ICollection containing the values in the Hashtable. 获取包含在Hashtable中的值的集合。 |
下表列出了Hashtable类的一些常用方法:
S.N | 方法名称和用途 |
---|---|
1 | Public Overridable Sub Add (key As Object, value As Object ) Adds an element with the specified key and value into the Hashtable. 将具有指定键和值的元素添加到Hashtable中。 |
2 | Public Overridable Sub Clear Removes all elements from the Hashtable. 从哈希表中移除所有元素。 |
3 | Public Overridable Function ContainsKey (key As Object) As Boolean Determines whether the Hashtable contains a specific key. 确定哈希表是否包含特定键。 |
4 | Public Overridable Function ContainsValue (value As Object) As Boolean Determines whether the Hashtable contains a specific value. 确定哈希表是否包含特定值。 |
5 | Public Overridable Sub Remove (key As Object) Removes the element with the specified key from the Hashtable. 使用指定的键从哈希表中删除元素。 |
示例:
下面的例子演示了这个概念:
- Module collections
- Sub Main()
- Dim ht As Hashtable = New Hashtable()
- Dim k As String
- ht.Add("001", "Zara Ali")
- 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 Saikia")
- If (ht.ContainsValue("Nuha Ali")) Then
- Console.WriteLine("This student name is already in the list")
- Else
- ht.Add("008", "Nuha Ali")
- 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
当上述代码被编译和执行时,它产生以下结果:
- 006: M. Arif
- 007: Ritesh Saikia
- 008: Nuha Ali
- 003: Joe Holzner
- 002: Abida Rehman
- 004: Mausam Banazir Nur
- 001: Zara Ali
- 005: M. Amlan
转载本站内容时,请务必注明来自W3xue,违者必究。