' 字典(Dictionary)是VB.NET中非常实用的集合类型,它存储键值对(key-value pairs),允许通过键快速查找值。下面是VB.NET中字典的完整用法指南。
' 1. 创建和初始化字典
' 导入命名空间
Imports System.Collections.Generic
' 创建空字典
Dim dict1 As New Dictionary(Of String, Integer)
' 创建并初始化字典(VB.NET 10.0+)
Dim dict2 As New Dictionary(Of String, String) From {
{"key1", "value1"},
{"key2", "value2"}
}
' 指定初始容量(当你知道大概大小时可提高性能)
Dim dict3 As New Dictionary(Of Integer, String)(100)
' 2. 添加元素
' 添加单个元素
dict1.Add("apple", 1)
dict1.Add("banana", 2)
' 使用索引器添加/更新元素
dict1("orange") = 3 ' 添加
dict1("apple") = 5 ' 更新
' 3. 访问元素
' 使用键访问值
Dim value As Integer = dict1("apple")
' 安全访问(避免KeyNotFoundException)
If dict1.TryGetValue("banana", value) Then
Console.WriteLine($"Banana value: {value}")
Else
Console.WriteLine("Key not found")
End If
' 检查键是否存在
If dict1.ContainsKey("orange") Then
Console.WriteLine("Orange exists in dictionary")
End If
' 检查值是否存在
If dict1.ContainsValue(5) Then
Console.WriteLine("Value 5 exists in dictionary")
End If
' 4. 遍历字典
' 遍历所有键值对
For Each kvp As KeyValuePair(Of String, Integer) In dict1
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
Next
' 只遍历键
For Each key As String In dict1.Keys
Console.WriteLine($"Key: {key}")
Next
' 只遍历值
For Each val As Integer In dict1.Values
Console.WriteLine($"Value: {val}")
Next
' 5. 修改和删除元素
' 更新值
dict1("apple") = 10
' 删除元素
dict1.Remove("banana")
' 安全删除(先检查是否存在)
If dict1.ContainsKey("orange") Then
dict1.Remove("orange")
End If
' 清空字典
dict1.Clear()
' 6. 其他常用属性和方法
' 获取元素数量
Dim count As Integer = dict1.Count
' 获取键或值的集合
Dim keys As Dictionary(Of String, Integer).KeyCollection = dict1.Keys
Dim values As Dictionary(Of String, Integer).ValueCollection = dict1.Values
' 转换为数组
Dim keyArray As String() = dict1.Keys.ToArray()
Dim valueArray As Integer() = dict1.Values.ToArray()
' 7. 自定义键类型
' 当使用自定义类型作为键时,需要重写GetHashCode和Equals方法:
Public Class Person
Public Property Id As Integer
Public Property Name As String
Public Overrides Function GetHashCode() As Integer
Return Id.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, Person)
If other Is Nothing Then Return False
Return Me.Id = other.Id
End Function
End Class
' 使用自定义键
Dim personDict As New Dictionary(Of Person, String)
Dim p1 As New Person With {.Id = 1, .Name = "Alice"}
personDict.Add(p1, "Manager")
' 8. 线程安全考虑
' 标准字典不是线程安全的。如果需要在多线程环境中使用:
' 使用并发字典
Imports System.Collections.Concurrent
Dim concurrentDict As New ConcurrentDictionary(Of String, Integer)
concurrentDict.TryAdd("key1", 1)
concurrentDict.TryUpdate("key1", 2, 1)
concurrentDict.TryRemove("key1", value)
' 9. 性能考虑
' 字典的查找、插入和删除操作平均时间复杂度为O(1)
' 初始容量设置合理可以减少重新哈希的次数
' 避免频繁的添加和删除操作,这可能导致内存碎片
' 10. 常见使用场景
' 1. 计数器
Dim wordCount As New Dictionary(Of String, Integer)
For Each word In words
If wordCount.ContainsKey(word) Then
wordCount(word) += 1
Else
wordCount.Add(word, 1)
End If
Next
' 2. 缓存
Dim cache As New Dictionary(Of String, Object)
If Not cache.ContainsKey("data") Then
cache("data") = GetExpensiveData()
End If
Dim data = cache("data")
' 3. 快速查找表
Dim productLookup As New Dictionary(Of Integer, Product)
For Each product In products
productLookup.Add(product.Id, product)
Next
Dim desiredProduct = productLookup(123)
' 以上是VB.NET字典的完整用法总结,涵盖了从基本操作到高级用法的各个方面。
03-26