Reputation: 121
i have an array
Dim A1 as array = { 4, 2, 7 }
i have an second array
Dim A2 as array = {{1, 21, 13}, {4 , 2, 7}, {5, 4, 5}}
how can i find A1 in A2 with Array.Find() method?
Thanks
Upvotes: 1
Views: 1273
Reputation: 25027
As a System.Array contains Objects, it is messy:
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
Swap the commented and un-commented equivalents to show that it works with both.
I'm not saying it will work in a general case.
Upvotes: 0
Reputation: 9041
Here is the closet thing I could think of that does what you're wanting with the Find()
method.
If you change your 2D array to a List(Of Integer())
you can do the following:
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
See running example here: https://dotnetfiddle.net/lDxQlW
Results:
Array 4,2,7 found
Upvotes: 1