我认为您不了解字典的工作原理。字典的值通过其唯一键访问。在内部使用密钥生成的哈希码查找它们。要正常工作,哈希码需要一些属性:
哈希码由GetHashCode
可能被任何类型覆盖的函数生成。您List(Of Object)
用作键值。List(Of Object)
不覆盖GetHashCode
. 它使用 Object 类型的默认实现。尽管此实现符合规定的要求,但它绝对不是您想要的。
我注意到您尝试用作键的列表始终具有相同的结构:一个整数、一个字符串和另一个整数。List(Of Object)
不是钥匙的好选择。但也许你可以创建一个可以用作键的类型:
Public Class MyKey
Private ReadOnly _firstValue As Integer
Private ReadOnly _secondValue As String
Private ReadOnly _thirdValue As Integer
Public Sub New(firstValue As Integer, secondValue As String, thirdValue As Integer)
_firstValue = firstValue
_secondValue = secondValue
_thirdValue = thirdValue
End Sub
Public ReadOnly Property FirstValue As Integer
Get
Return _firstValue
End Get
End Property
Public ReadOnly Property SecondValue As String
Get
Return _secondValue
End Get
End Property
Public ReadOnly Property ThirdValue As Integer
Get
Return _thirdValue
End Get
End Property
Public Overloads Function GetHashCode() As Integer
Dim hashCode As Integer = 31
hashCode = hashCode + 17 * _firstValue
hashCode = hashCode + 17 * _secondValue.GetHashCode()
hashCode = hashCode + 17 * _thirdValue
Return hashCode
End Function
Public Overloads Function Equals(obj As Object) As Boolean
If TypeOf obj Is MyKey Then
Dim other As MyKey = CType(obj, MyKey)
Return _firstValue = other._firstValue And
_secondValue = other._secondValue And
_thirdValue = other._thirdValue
Else
Return False
End If
End Function
End Class
此类型可用于字典键。它产生一个适当的哈希码并覆盖Equals
以比较内容而不是引用。此外,确保哈希码永远不会改变是不可变的。
字典需要唯一的键。由于您的键不是唯一的,因此值必须是 List(Of Integer) 类型。添加一个值需要一些额外的工作。首先,您必须检查该键是否已存在于字典中。如果不创建新条目:
Dim dictionary As New Dictionary(Of MyKey, List(Of Integer))
Add(dictionary, New MyKey(12, "SomeString", 3), 54)
Add(dictionary, New MyKey(8, "SomeAnotherString", 3), 6)
Add(dictionary, New MyKey(12, "SomeString", 3), 15)
Public Sub Add(dictionary As Dictionary(Of MyKey, List(Of Integer)), key As MyKey, value As Integer)
Dim list As List(Of Integer) = Nothing
If Not dictionary.TryGetValue(key, list) Then
list = New List(Of Integer)()
dictionary.Add(key, list)
End If
list.Add(value)
End Sub