binaryseach of an arraylist

  • Thread starter Thread starter Bernie Yaeger
  • Start date Start date
B

Bernie Yaeger

I'm having difficulty searching an arraylist for certain values that are in
another arraylist. Essentially, I want to load the second arraylist with
only one of each of the possible elements in the first arraylist. Thus if
singlearraylist contains "ww", "l2", "s1", "ww", "cc", "s1" I only want
marraylist to have "ww", "l2", "s1", "cc". The search seems to fail
regardless what I do, and the result is that marraylist has virtually all of
the elements from singlearraylist. Here's my code:
For i = 0 To singlearraylist.Count - 1

searchobj = singlearraylist(i)

ifind = marraylist.BinarySearch(searchobj)

If ifind < 0 Then ' ie, not found

marraylist.Add(singlearraylist(i))

End If

Next

Tx for any help.

Bernie Yaeger
 
OK, figured it out - I have to continually sort the arraylist as I add
items - binarysearch only works against a sorted arraylist.

Tx - Bernie
 
Hi Bernie,

There's a more efficient way of doing this which doesn't requires any
searching or sorting (except once at the start).

Sort the singlearraylist. Then go through the sorted array copying values
unless they have already been copied.

Dim sLastValue As String = ""
For Each sValue As String In singlearraylist
If sValue <> sLastValue Then
marraylist.Add (sValue)
sLastValue = sValue
End If
Next

Regards,
Fergus
 
Bernie,
In addition to Fergus's comments.

Have you considered using a SortedList instead of an ArrayList.

As SortedLists are automatically sorted and support finding the item by a
key.

The problem is if the objects you are dealing with do not have a good 'key'
or do not make good 'keys'.

If the objects don't really have keys I would use Fergus's idea.

Hope this helps
Jay
 
Tx Fergus, Jay,

A sortedlist would not apply here, correct, as making good keys would be a
problem. Tx to you both.

Bernie
 
Back
Top