Comparing an array with another array

ayozzhero

Well-known member
Joined
Apr 6, 2005
Messages
186
Location
Malaysia
Programming Experience
1-3
Is there in VB .Net a function similar to array_diff in PHP. I am comparing 2 arrays, searching for:
1. Items which exist in array A but not in array B
2. Items which exist in both arrays


Thank you.
 
Not that I'm aware of, but with the help of generics and delegation you can create your own methods to do both very easily.
VB.NET:
Private arr2 As Array

''' <summary>
''' Gets an array containing all elements that are contained in one array but not another.
''' </summary>
''' <typeparam name="T">
''' The type of the elements in both source arrays and the array returned by the method.
''' </typeparam>
''' <param name="arr1">
''' The array in which the returned elements are present.
''' </param>
''' <param name="arr2">
''' The array in which the returned elements are not present.
''' </param>
''' <returns>
''' An array containing the elements that are present in the first array but not the second.
''' </returns>
Public Function GetUniqueElements(Of T)(ByVal arr1 As T(), ByVal arr2 As T()) As T()
    Me.arr2 = arr2

    Return Array.FindAll(arr1, New Predicate(Of T)(AddressOf IsObjectNotInArray(Of T)))
End Function

''' <summary>
''' Gets an array containing all elements that are contained in both of two arrays.
''' </summary>
''' <typeparam name="T">
''' The type of the elements in both source arrays and the array returned by the method.
''' </typeparam>
''' <param name="arr1">
''' The first source array.
''' </param>
''' <param name="arr2">
''' The second source array.
''' </param>
''' <returns>
''' An array containing the elements that are present in both source arrays
''' </returns>
Public Function GetCommonElements(Of T)(ByVal arr1 As T(), ByVal arr2 As T()) As T()
    Me.arr2 = arr2

    Return Array.FindAll(arr1, New Predicate(Of T)(AddressOf IsObjectInArray(Of T)))
End Function

Private Function IsObjectInArray(Of T)(ByVal obj As T) As Boolean
    Return (Array.IndexOf(Me.arr2, obj) <> -1)
End Function

Private Function IsObjectNotInArray(Of T)(ByVal obj As T) As Boolean
    Return Not Me.IsObjectInArray(obj)
End Function
You could put that code in a utility library and call the GetUniqueElements and GetCommonElements methods whenever and wherever they were needed.
 
Back
Top