我正在使用新的编码,并且正在开发一个小型应用程序,以简化某些流程。
我正在尝试从列表框中删除某个条目。
这是列表框包含的示例: 54 54 56 56 58 60 60
如何删除不重复的条目?在这种情况下,将删除58。
列表框中的条目数可以在1到8之间变化。
我已经尝试过通过遍历列表框进行多种操作,但是没有什么方法可以解决问题。
For i = 0 To ListBox1.Items.Count - 1 Step 2
If ListBox1.Items(i) <> ListBox1.Items(i + 1) Then
ListBox1.Items.RemoveAt(i)
End If
Next
我在做什么错? 预先感谢!
答案 0 :(得分:0)
此解决方案不太好,但是它可以按任意顺序适用于任意数量的列表项。您在很大程度上依赖于列表的顺序和分组。
行中的评论。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Create a list to hold the indexes to remove
Dim RemoveIndex As New List(Of Integer)
'put the items in the list box into an array of Integers
Dim Numbers = (From n In ListBox1.Items
Select CInt(n)).ToArray
'Loop through the numbers that came from the list box
For i = 0 To Numbers.Count - 1
'.LastIndexOf looks in the array (starting at the beginning each time) for Numbers(i)
Dim LastIndex = Array.LastIndexOf(Numbers, Numbers(i))
'If it is not the item we are searching for
If LastIndex <> i Then
'Add both to the list
RemoveIndex.Add(LastIndex)
RemoveIndex.Add(i)
End If
Next
'Remove duplicates from the list. We can't remove the same item twice
'Order by the highest index first. That way we won't mess up the lower indexes
'and we will remove the item/index we expect.
Dim DistinctList = RemoveIndex.Distinct().OrderByDescending(Function(x) x)
'Loop through the list (remember the highest index is first)
For Each index In DistinctList
ListBox1.Items.RemoveAt(index)
Next
End Sub