[英]vb.net — Using arraylist as key in dictionary
Dim dct As New Dictionary(Of ArrayList, ArrayList)
' Populate Dictionary
dct.Add(New ArrayList({"Dot", "0"}), New ArrayList({20, 30, 40,> 50}))
dct.Add(New ArrayList({"Dot", "1"}), New ArrayList({120, 130, 140,> 150}))
' Search in dictionary
Dim al As New ArrayList({"Dot", "2"})
If dct.ContainsKey(al) Then ' does not work****
MessageBox.Show("Found: " & al(0).ToString)
End If
为了使字典正常工作,如果键的值相同,则它们必须相等。 您的字典使用ArrayList.Equals()方法比较数组列表。 该方法不会执行您所需的操作,仅当数组列表是同一对象时才返回True。
您将需要使用字典构造函数,以使您可以通过比较器。 使它看起来像这样:
Dim dct As New Dictionary(Of ArrayList, ArrayList)(new MyComparer())
MyComparer类是一个实现IEqualityComparer(Of ArrayList)的比较器。 一个可能的实现可能是这样的:
Class MyComparer
Implements IEqualityComparer(Of ArrayList)
Public Function Equals1(ByVal x As System.Collections.ArrayList, ByVal y As System.Collections.ArrayList) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of System.Collections.ArrayList).Equals
If x.Count <> y.Count Then Return False
For ix As Integer = 0 To x.Count - 1
If Not x(ix).Equals(y(ix)) Then Return False
Next
Return True
End Function
Public Function GetHashCode1(ByVal obj As System.Collections.ArrayList) As Integer Implements System.Collections.Generic.IEqualityComparer(Of System.Collections.ArrayList).GetHashCode
Return obj.Count.GetHashCode
End Function
End Class
那是因为它执行参考比较,而您期望它进行值比较。
两个arrayList的内容都相同,但是没有指向同一实例,因此失败。
编辑:另外,当字典中不存在此词时,为什么还要找到这个( al
)?
您创建一个新的ArrayList
并且不将其添加到字典中。 您为什么希望在词典中找到它?
您需要先将新的ArrayList
添加到字典中,然后才能在其中找到它。
您有两个具有相同内容的不同 ArrayList
对象。 但是它们仍然是不同的对象,一个在字典中,另一个不在字典中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.