簡體   English   中英

在ArrayList VB.NET中查找整數數組

[英]Find Integer array in ArrayList 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

盡管ArrayList確實包含“ New Integer(){1,2}”,但即使我嘗試這樣做,也不會顯示MsgBox:

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

它根本不會顯示。

提前致謝。

- - - - - - - -編輯 - - - - - - - -

我最終決定只比較Integer列表的值,如下所示:

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沒有內置機制可以在array之間進行值比較 您將必須從頭開始實現自己的EqualityComparer

除非。

您不會說這些數組從何而來。 如果您能夠管理這些數組,以便可以將該數組與相同的引用進行比較,則可以進行以下工作:

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())

我不確定列表是否接受您正在執行的初始化(新{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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM