Comparing an array

doc7213

New member
Joined
Jul 2, 2008
Messages
4
Programming Experience
Beginner
I have an array that I need all elements compared to each other and if equal, one of the elements reset to nothing. Currently I have

Dim first as integer
Dim second as integer
Dim Array() as array

For second = 1 to 155
If Array(first) = Array(second) Then
Array(second) = ""
End If
Next second

All this does is keep the first element in the array and reset everything else to ""
Any direction would be helpful
 
If you're stuck in Studio 2005, the following will get you started, but is pretty innefficent:

VB.NET:
Dim currentValueToCheck As String
Dim myArray() As String = {"1", "2", "3", "4", "5", "1", "2", "3", "4", "6"}

For currentIndex As Integer = 0 To myArray.GetUpperBound(0)
  currentValueToCheck = CStr(myArray.GetValue(currentIndex))

  For searchIndex As Integer = currentIndex + 1 To myArray.GetUpperBound(0)
    If CStr(myArray.GetValue(searchIndex)) = currentValueToCheck Then
      myArray.SetValue("", searchIndex)
    End If
  Next
Next


If you're able to upgrade your project to Studio 08, thus enabling LINQ, you get a much more elegant: (Assuming you can drop duplicate entries, instead of just "blanking" them out.)

VB.NET:
Dim withPossibleDuplicates() As String = {"1", "2", "3", "1", "2", "4"}

Dim query = From entries In withPossibleDuplicates _
                    Distinct

Dim withNoDuplicates As New List(Of String)
For Each result In query
 withNoDuplicates.Add(result)
Next
 
Oh, also, I meant to include but forgot:

Save yourself a lot of headaches in your debugging and get out of the habit of using type similar names as your variable names:

i.e.

Dim Array() as array

While it works, its confusing, and late at night hours into your code you may find yourself regretting it as I once did.

You'll notice in my example I modified this to at LEAST be "Dim myArray" so there is some degree of difference; however, SPECIFIC naming is far far superior. You'll see in my second example I crafted up, I use things like "withPossibleDuplicates" which provide a highly descriptive name of what that variable should contain.
 
Thank you for the quick reply and advice. I will implement and let you know how it turns out. Works like a charm. You saved me a big head ache. Thank you again.
 
Back
Top