问题
Hello I am having troubles with my application. I am trying to load a list into listbox1 and then refresh the same list in listbox2 (but with possibly different results) and then compare the two and display in textbox1 the differences between the two list boxes. I have gotten to a point where I am able to tell if there are differences but when it goes to post into the textbox it displays the entire listbox and not the differences.
That's a little wordy. Sorry. Below is my code:
TextBox1.Text = ""
Dim Folder As String = My.Settings.path
ListBox2.Items.Clear()
For Each File As String In My.Computer.FileSystem.GetFiles _
(Folder, FileIO.SearchOption.SearchAllSubDirectories)
ListBox2.Items.Add(IO.Path.GetFileName(File))
Next
' This is where the issues is - The system compares the items and displays all items in the textbox.
For Each item In ListBox1.Items
If item.ToString = ListBox2.Items.ToString Then
Else
TextBox1.Text += (Environment.NewLine + item.ToString)
End If
Next
Thanks for your help.
回答1:
You can use LINQ. This example will find all items in ListBox1
not in ListBox2
:
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)
回答2:
If I understand you correctly, you want a list of the differences between the two lists.
Meaning, a list that contains the elements in the first list that are not present in the second list and elements that are present in the second list that are not present in the first one
Dim list1 = from li in listBox1.Items select li
Dim list2 = from li in listBox2.Items select li
Dim list3 = list1.Except(list2).Union(list2.Except(list1))
textBox1.Text = string.Join(Environment.NewLine, list3)
来源:https://stackoverflow.com/questions/22125305/comparing-two-list-box-and-displaying-the-differences-vb-net