从列表框中删除特定项目 - vb.net

Remove a specific item from Listbox - vb.net

我仍然是新手,我正在开发一个小应用程序来简化某些流程。

我正在尝试从列表框中删除某个条目。

这是列表框包含的示例: 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

我做错了什么? 提前致谢!

这个解决方案不太优雅,但它应该适用于以任何顺序排列的任意数量的列表项。您在很大程度上依赖于列表的顺序和分组。

在线评论。

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