【发布时间】:2020-10-13 16:10:52
【问题描述】:
如何删除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
【问题讨论】:
-
是否应该将其 Dim 移除Dups As New List(Of String) = oList.Distinct().ToList
-
Distinct()返回一个枚举器。你可以做Debug.Print("Total number of cylinders = " & oList.Distinct().Count())。使用HashSet<T>而不是List<T>可能更合理。 -
newList = oList.Distinct().ToList()Distinct 是一种返回新列表的方法,但它使用默认的相等比较器工作,而不仅仅是对象中的名称或某些文本喜欢你在那里做的事情 -
Enumerable.Distinct是一种 LINQ 扩展方法,它返回没有重复的序列(如果类型覆盖GetHashCode+Equals类似字符串)。由于您想从列表中删除重复项,您必须将它们重新分配给列表变量:oList = oList.Distinct().ToList()。ToList使用不同的字符串创建一个新列表。
标签: vb.net list duplicates