从List(Of T)中移除重复项

时间:2016-05-20 14:43:41

标签: vb.net list duplicates

如何删除List(Of String)中的重复项?我假设它可以与List(Of T).Distinct一起使用,但我的结果却不然。我究竟做错了什么?或者我需要更改哪些内容才能删除List(Of T)中的重复项?

我在世界各地的网上读过关于哈希的东西,但我认为这不是必要的。

这是我生成列表的代码(适用于Autodesk Inventor)。

Private Function CountCylinders(ByVal oDef As AssemblyComponentDefinition) As Integer

    ' Lets list all cylinder segments found in the assembly
    ' we will need the document name to do this.
    ' the initial value is nothing, if, after counting
    ' this is still the case, there are no cylinders.
    Dim oList As New List(Of String)

    ' Loop through all of the occurences found in the assembly
    For Each oOccurrence As ComponentOccurrence In oDef.Occurrences

        ' Get the occurence document
        Dim oOccurenceDocument As Document
        oOccurenceDocument = oOccurrence.Definition.Document

        ' Check if the occurence document name contains cylinder
        If oOccurenceDocument.FullFileName.Contains("Cylinder") Then
            ' Get the cylinder filename
            Dim oCylinder As String
            oCylinder = oOccurenceDocument.FullFileName

            ' Get the filename w/o extension
            oCylinder = IO.Path.GetFileNameWithoutExtension(oCylinder)

            ' Remove the segment mark.
            oCylinder = oCylinder.Remove(oCylinder.LastIndexOf("_"), oCylinder.Length - oCylinder.LastIndexOf("_"))

            oList.Add(oCylinder)
            Debug.Print("add : " & oCylinder)
        End If
    Next

    ' Delete the duplicates in the list
    oList.Distinct()

    ' TODO: can be removed.
    Debug.Print("Total number of cylinders = " & oList.Count)

    ' Return the number of cylinders
    CountCylinders = oList.Count

End Function

以下是代码中的调试输出:

add : Cylinder_1
add : Cylinder_2
add : Cylinder_2
add : Cylinder_2
add : Cylinder_2
add : Cylinder_2
add : Cylinder_7
Total number of cylinders = 7

3 个答案:

答案 0 :(得分:1)

这是您要寻找的答案,这要感谢dotnetperls.com VB.NET Remove Duplicates From List

ListOfString.Distinct().ToList

答案 1 :(得分:0)

Function RemoveDuplicate(ByVal TheList As List(Of String)) As List(Of String)
    Dim Result As New List(Of String)

    Dim Exist As Boolean = False
    For Each ElementString As String In TheList
        Exist = False
        For Each ElementStringInResult As String In Result
            If ElementString = ElementStringInResult Then
                Exist = True
                Exit For
            End If
        Next
        If Not Exist Then
            Result.Add(ElementString)
        End If
    Next

    Return Result
End Function

答案 2 :(得分:-1)

导入System.Linq

将您的列表设为新列表(字符串)

YOURList.Add(item.Text)

您的列表= YOURList.Distinct.ToList

必须包含System.Linq

相关问题