且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除列表中的重复条目

更新时间:2022-04-27 08:49:06

为此创建了列表删除,但是它删除了列表中的第一个类似项目:
http://msdn.microsoft.com/en-us/library/cd666k3e.aspx [ ^ ]
The list remove was created for this purpose, however it deletes the first simular item in the list:
http://msdn.microsoft.com/en-us/library/cd666k3e.aspx[^]


我听不懂列表"的意思. "List(Of T)"或"ListBox"或其他内容...
因此,我将给出一个大致的答案.
从列表中删除项目时,该列表的项目数减少.这就是为什么固定循环无法按预期工作的原因.我在下面编写了一个方法,该方法删除ListBox对象中的重复项.您可以根据自己的目的调整此方法...
I couldn''t understand what you mean by "List". "List(Of T)" or "ListBox" or something else...
So I will give a general answer.
When you remove an item from a list, item count of this list decreases. This is why fixed loops don''t work as expected. I wrote a method below that removes duplicated items in a ListBox object. You can adapt this method to your purpose...
Private Sub RemoveDupItems(ByRef ListBoxObj As ListBox)
    Dim ItemCount As Integer = ListBoxObj.Items.Count
    Dim Position1 As Integer = 0

    While (Position1 < ItemCount)
        Dim Position2 As Integer = 0
        While (Position2 < ItemCount)
            If Position1 <> Position2 Then
                If ListBoxObj.Items(Position1) = ListBoxObj.Items(Position2) Then
                    ListBoxObj.Items.RemoveAt(Position2)
                    ItemCount -= 1
                    Exit While
                End If
            End If
            Position2 += 1
        End While
        Position1 += 1
    End While
End Sub


用法示例:


Usage example:

RemoveDupItems(ListBox1)