views:

28

answers:

2

I have two arraylists, and I would like to have a new arraylist with only the uncommon items.

Is this the "best" or at least decent way to do it?

Public Function diffLists(ByRef first, ByRef second As Collection) As ArrayList
    Dim retval As New ArrayList()
    For Each element In first
        If Not second.Contains(element) Then
            retval.Add(element)
        End If
    Next
    retval.TrimToSize()
    Return retval
End Function

TIA

+1  A: 

That's not a good way because it only gives you elements from the first list that are not in the second not elements that are not in both lists (as I understand your question to be).

Either way, the best way to accomplish this is probably to use Linq. If you wanted a better way to do what you're doing, you could use the Except method like so

first.Except(second)

However, if you really want the difference between the two, you'll need get a Union of the two lists (which will also filter out duplicates) and then exclude the elements that are in both.

first.Union( second )
   .Except( first.Intersect(second) );

This approach also has the added benefit of stating what you want done (intent) as opposed to how to approach the task (specific implementation).

R0MANARMY
A: 

I'm not familiar with VB, but in general, the "best" way to do this is to sort both the arrays, then compare the elements side-by-side, discarding equal elements along the way.

In pseudo-code:

Sort(A)
Sort(B)
I = 0, J = 0, K = Min(A.Length, B.Length)
While I < K And J < K
  If A[I] == B[J]
    I++
    J++
  Else If A[I] < B[J]
    Add A[I] to resultant list
    I++
  Else // B[J] must be < A[I]
    Add B[J] to resultant list
    J++
  End If
End While
If I < A.Length
  Add remaining elements of A to resultant list
Else If J < B.Length
  Add remaining elements of B to resultant list
End If
casablanca
If you can guarantee that elements in the list are unique (list is a set) there's an easier way with combining the sets into a single list, sorting the elements and throwing out those of which there are two.
R0MANARMY