Link to home
Start Free TrialLog in
Avatar of hdgh
hdghFlag for Canada

asked on

vb 2008 - Comparing Array elements

Is there any way in VB 2008 to compare two arrays to find elements missing from arrary1 in array2?
Avatar of carlnorrbom
carlnorrbom
Flag of Sweden image

Hi,

You can iterate over Array2 and compare the current element in Array2 with the corresponding element in Array1 but that would require both arrays having the same upper bound, i.e. all elements have either a value or null.

/Carl.
Hi,

Just realized a bit of code could be handy, sorry.

/Carl.
        Dim Array1() As String = {"Value1", "Value2", "Value3", "Value4"}
        Dim Array2() As String = {"Value1", "Value2", "", "Value4"}
        Dim i As Integer = 0
        Do While i <= UBound(Array2)
            If Not String.Compare(Array2(i).ToString, Array1(i).ToString) = 0 Then
                Throw New Exception("Array Element " & i.ToString & " in Array1 is missing or not the same as in Array2")
            End If
            i += 1
        Loop

Open in new window

Avatar of hdgh

ASKER

Thanks for your reply.

the arrays may be of different size ( ary1 = 200 ele ; ary2 300 ele).  I need to determine if the values of  ary1 are missing from ary2.

I have the following....my logic must be wrong....another set of eyes would help !! ( see code snippet)


    Dim ary1() As String = {"123456789", "123456787", "123456788", "185456478", "184576781", "999199912"}
    Dim ary2() As String = {"123456789", "999123124", "123499541", "123456787", "123456788", "185456478", "184576781"}
    Dim bFound, bNoDiff As Boolean
    bNoDiff = True
 
    Array.Sort(ary1)
    Array.Sort(ary2)
    bNoDiff = True
 
    For intX = 0 To UBound(ary1)
      bFound = False
      For intY = 0 To UBound(ary2)
        If Array.BinarySearch(ary1, ary2(intY).ToString) Then
          bFound = True
          Exit For
        End If
      Next
      If bFound = False Then
        bNoDiff = False
        MsgBox("Missing: " & ary1(intX))
      End If
    Next
 
    If bNoDiff Then
      MsgBox("0 Differences Found")
    End If

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hdgh
hdgh
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial