在 vb.net 中使用 Array.Find() 方法在数组中搜索数组

Array seach in array with Array.Find() method in vb.net

我有一个数组

Dim A1 as array = { 4, 2, 7 }

我有第二个数组

Dim A2 as array = {{1, 21, 13}, {4 , 2, 7}, {5, 4, 5}} 

如何使用 Array.Find() 方法在 A2 中找到 A1?

谢谢

这是我能想到的最实用的东西,它可以用 Find() 方法满足您的需求。

如果您将二维数组更改为 List(Of Integer()),您可以执行以下操作:

Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Module Module1

    Public Sub Main()
        Dim A1() as Integer = {4, 2, 7}
        Dim A2 As New List(Of Integer())
        A2.Add(New Integer() {1, 21, 13})
        A2.Add(New Integer() {4, 2, 7})
        A2.Add(New Integer() {5, 4, 5})

        Dim A3 = A2.Find(Function(A) A.SequenceEqual(A1))
        If Not A3 Is Nothing Then
            Console.WriteLine(String.Format("Array {0} found", String.Join(",", A1)))
        Else
            Console.WriteLine(String.Format("Array {0} not found", String.Join(",", A1)))
        End If
    End Sub
End Module

请参阅此处的 运行 示例:https://dotnetfiddle.net/lDxQlW

结果:

Array 4,2,7 found

由于System.Array包含对象,所以很乱:

Option Strict On
Option Infer Off

Module Module1

    Function ArrayEquals(a As Array, b As Array) As Boolean
        If a Is Nothing AndAlso b Is Nothing Then
            Return True
        End If

        If a Is Nothing OrElse b Is Nothing Then
            Return False
        End If

        If a.Length <> b.Length Then
            Return False
        End If

        For i As Integer = 0 To a.GetUpperBound(0)
            If Not a.GetValue(i).Equals(b.GetValue(i)) Then
                Return False
            End If
        Next

        Return True

    End Function

    Sub Main()
        'Dim a As Array = {"a", "b", "c"}
        'Dim b As Array = {"d", "e", "f"}
        'Dim c As Array = {"g", "h", "i"}
        Dim a As Array = {1, 2, 3}
        Dim b As Array = {2, 3, 1}
        Dim c As Array = {3, 1, 2}

        Dim x As Array = {a, b, c}

        'Dim toFind As Array = {"d", "e", "f"}
        Dim toFind As Array = {2, 3, 1}

        Dim p As Object = Array.Find(CType(x, Object()), Function(z) ArrayEquals(CType(z, Array), toFind))

        If p Is Nothing Then
            Console.WriteLine("Not found.")
        Else
            ' Visualize the result:
            Select Case p.GetType().ToString()
                Case Is = "System.Int32[]"
                    Dim q As Int32() = DirectCast(p, Int32())
                    Console.WriteLine(String.Join(", ", q))
                Case Is = "System.String[]"
                    Dim q As String() = DirectCast(p, String())
                    Console.WriteLine(String.Join(", ", q))
            End Select

        End If

        Console.ReadLine()

    End Sub

End Module

交换注释和未注释的等效项以表明它适用于两者。

我并不是说它在一般情况下都有效。