我仍然是新的编码,我正在开发一个小的应用程序来平滑一些过程。
我正在尝试从列表框中删除某个条目。
这是列表框所包含内容的一个示例: 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
我做错了什么?提前感谢!
发布于 2019-05-20 01:25:21
这个解决方案不是很优雅,但它应该适用于任何顺序的任意数量的列表项。您很大程度上依赖于列表的顺序和分组。
行中的注释。
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
https://stackoverflow.com/questions/56208141
复制相似问题