I am writing an application to compare each item on listbox1 to all items on listbox2. If the item is found, then remove it from both lists. The goal is to only have the items that were not found remain on both lists.
The problem is, the application just hangs and I never get any results. I looked at my code several times and I cannot figure out what’s going on (programming noob I know…).
Can anybody help me with this?
Code Snippet:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim a As String
Dim b As String
Dim y As String
For i As Integer = 0 To ListBox1.Items.Count - 1
a = ListBox1.Items(i)
y = 1
Do While y = 1
For x As Integer = 0 To ListBox2.Items.Count - 1
b = ListBox2.Items(x)
Dim res As Int16 = String.Compare(a, b)
If res = 0 Then
y = 0
ListBox2.Items.Remove(i)
ListBox2.Items.Remove(x)
ElseIf x = ListBox1.Items.Count Then
Exit Do
End If
Next
Loop
Next
End Sub
if ListBox1.Items.Count is more that ListBox2.Items.Count – 1, X will never equal ListBox1.Items.Count, so the Exit Do will never run, and the code will just loop endlessly in the
Have you considered using Linq for example, for easier list management?
edit: Additionally it’s wrong to delete an item from the list you are traversing with a for (it’s downright illegal to do that with a For Each) because each deletion will offset the loop counter.
edit2: here’s a Linq snippet that accomplishes the task:
what is does is basically extract the strings from both list (this is necessary because the ListBox.Items collection is a little weird)
After that we run the intersect method and copy the results into a list. (the .ToList part)
The copying is a required part because, otherwise dupes would just be a subset of the Items of the ListBox, and once again we would be trying to lift ourselves by pulling on our shoestrings.
The last part is just a simple delete loop, that removes the items from the collection