me.user
me.user

Reputation: 35

How do I compare two listboxes?

I have two listboxes (1: Primary, 2:Secondary). These listboxes contain numbers. The Primary Listbox contains 7 numbers, and the Secondary Listbox contains 6 numbers.

enter image description here

I want to compare the values of the Primary Listbox to those of the Secondary. This comparison should yield three results:

Result #1: X number of values were found to be common.

enter image description here

Result#2: All numbers matched.

enter image description here

Result#3: No matches found.

enter image description here

This is what I have so far:

If lstPrimaryNumbers.Items.Count = 0 Or lstSecondaryNumbers.Items.Count = 0 Then
            MessageBox.Show("There is nothing to compare.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End If

        For i As Integer = 0 To lstPrimaryNumbers.Items.Contains
            For j As Integer = 0 To lstSecondaryNumbers.Items.Contains

                If i = j Then
                    MessageBox.Show(i & " " & j & " matched!")
                End If
            Next
        Next

PLEASE NOTE:

I HAVE CHANGED MY ENTIRE INTERFACE, SO THIS POST IS OBSOLETE AND I HAVE NO USE FOR IT NOW. THANK YOU EVERYONE FOR YOUR SUPPORT!

I will leave this for the moderators to decide whether to remove this post or keep it for other users reference.

I will flag this post.

Upvotes: 0

Views: 651

Answers (2)

Mary
Mary

Reputation: 15101

First, I got the contents of the ListBoxes into arrays with a little linq. Then using the .Intersect method found the matches. And displayed the .Count. You iterate the result with a For Each

Private Sub OPCode()
        Dim id1() As Integer = (From i In ListBox1.Items Select CInt(i)).ToArray
        Dim id2() As Integer = (From i In ListBox2.Items Select CInt(i)).ToArray
        Dim Matches As IEnumerable(Of Integer) = id1.Intersect(id2)
        MessageBox.Show(Matches.Count.ToString)
    End Sub
'TextBox1.Multiline = True is set at design time
'Expand the text box size so several lines will be visible
 For Each Match As Integer In Matches
      TextBox1.Text &= (CStr(Match) & Environment.NewLine)
 Next

Upvotes: 1

Steve
Steve

Reputation: 216363

The matching items could be found with

Dim r = lb1.Items.Cast(Of Int32).Where(Function (x) lb2.Items.Contains(x))
MessageBox.Show(String.Join(",", r) & " matched")

If you want to have a full match, then use IEnumerable.All to check

Dim a = lb1.Items.Cast(Of Int32).All(Function (x) lb2.Items.Contains(x))
If a Then
   MessageBox.Show("Full Match")
End If

Finally if you want only know if some items match then use IEnumerable.Any

Dim b = lb1.Items.Cast(Of Int32).Any(Function(x) lb2.Items.Contains(x))
If Not b Then
    MessageBox.Show("No matches where found")
End If

I have assumed that your items are integers, but if you add them as strings then you need to change the Cast(Of Int32) to Cast(Of String)

Upvotes: 2

Related Questions