在数组列表 VB.NET 中查找整数数组



所以我使用 ArrayLists 来存储一些整数数组,我遇到了以下问题:

Public Class Form1
Public ag As New ArrayList
Sub a() Handles Me.Load
ag.Add(New Integer() {1, 2})
If ag.Contains(New Integer() {1, 2}) Then
MsgBox("aaa")
End If
End Sub
End Class

MsgBox 不会显示,尽管 ArrayList 确实包含"New Integer(( {1, 2}",即使我尝试这样做:

Public Class Form1
Public ag As New ArrayList
Sub a() Handles Me.Load
ag.Add(New Integer() {1, 2})
Dim t = New Integer() {1, 2}
For Each it In ag
If it.Equals(t) Then
MsgBox("aa")
Exit For
End If
Next
End Sub
End Class

它根本不会显示。

提前谢谢。

---------------编辑---------------

我最终决定像这样比较整数列表的值:

Public Class Form1
Public ag As New List(Of Integer())
Sub a() Handles Me.Load
ag.Add(New Integer() {1, 2})
Dim t = New Integer() {1, 2}
For Each it In ag
If it(0) = t(0) And it(1) = t(1) Then
MsgBox("aa")
Exit For
End If
Next
End Sub
End Class

谢谢大家的回复。

数组是引用类型。默认情况下,引用类型对.Equals()=比较使用引用相等性。由于您在这两种情况下都与New Integer{1,2}进行比较(强调New(,因此您正在与两个不同的参考进行比较。即使两个数组具有相同的值,它们也是内存中的两个不同对象,每个对象都有自己不同的引用,因此引用比较将始终返回 false。

为了使这项工作按照您想要的方式进行,您需要进行值比较而不是引用比较。遗憾的是,.Net 中没有内置的机制来对数组进行值比较。您必须从头开始实现自己的 EqualComparer。

除非。

你没有说这些数组来自哪里。如果您能够管理这些数组,以便可以将该数组与相同的引用进行比较,则可以完成以下工作:

Public Class Form1
Public ag As New List(Of Integer())
Sub a() Handles Me.Load
Dim t As New Integer() {1,2}
ag.Add(t)
If ag.Contains(t) Then
MsgBox("aaa")
End If
End Sub
End Class

当我在这里时,您还应该将ArrayList更改为List(Of Integer()).

我不确定列表是否接受您正在执行的初始化(new {1,2(...(,但无论如何您可以使用 LINQ 来加速搜索:

dim ag as new ListOf(Integer)
ag.Add(1)
ag.Add(2)
dim WHat2Find as integer = 2
Dim Located As Integer = Ag.FindIndex(Function(y) y.Contains(What2Find))
If Located > -1
'  Found!
End If

最新更新