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
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
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.
This approach also has the added benefit of stating what you want done (intent) as opposed to how to approach the task (specific implementation).