Lacuna Lacuna - 5 months ago 21
Vb.net Question

Compare the values of two listboxes and add the non-equivalent values to a third listbox

My knowledge of programming is not too extensive but I have just finished my second year of higher education in computer engineering and have taken a few low level programming courses.

In Visual Basic, I am having trouble comparing the values of two

ListBox
controls and putting the values that aren't the same into another
ListBox
.

I need to compare the items of
ListBox2
to the items of
ListBox1
and if there are any items in
ListBox2
that are not in
ListBox1
, add them to
ListBox3
. I do not need to find the items in
ListBox1
that are not in
ListBox2
. I cannot use a loop to compare their values based on index because these lists are of names which will be constantly added to and removed from. I also cannot sort these ListBoxes.

There was an example for C# that I found here that used LINQ (I don't really know what that is) to compare the lists and then add the result to a
TextBox
control. However, I need to know how to add them to a
ListBox
and not a
TextBox
.

[EDIT] The example that I have tried is this:

Dim result As List(Of String) = (From s1 As String In Me.ListBox1.Items Where Not Me.ListBox2.Items.Contains(s1) Select s1).ToList()
Me.TextBox1.Text = String.Join(Environment.NewLine, result)

Answer
    Dim one As ListBox = New ListBox()
    Dim two As ListBox = New ListBox()
    Dim three As ListBox = New ListBox()
    Dim unique As Boolean = True

    For i As Integer = 0 To one.Items.Count
        For j As Integer = 0 To two.Items.Count
            If (one.Text = two.Text) Then
                unique = False
            Else
                two.SelectedIndex = j
            End If
        Next
        If (unique) Then
            three.Items.Add(one.Text)
        Else
            one.SelectedIndex = i
            unique = True
        End If
    Next

I believe this may be what you're looking for. What it does is compares each value in Listbox one to all values in Listbox two and if a value is seen to be a duplicate the Boolean flag unique is switched to false and the item is not added to Listbox three.

Comments