如何在
我在全球网络上读到了一些关于哈希的东西,但我认为这并不是必要的。
以下是生成列表的代码(适用于Autodesk Inventor)。
以下是我的代码调试输出结果:
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
Distinct()
返回一个枚举器。您可以使用Debug.Print("Total number of cylinders = " & oList.Distinct().Count())
。使用HashSet<T>
而不是List<T>
可能更合理。 - Nico SchertlernewList = oList.Distinct().ToList()
这里的 Distinct 方法会返回一个新的列表,但它使用默认的相等比较器进行操作,而不仅仅是对象中的名称或某些文本,这似乎是你在那里做的事情。 - Ňɏssa PøngjǣrdenlarpEnumerable.Distinct
是一个LINQ扩展方法,它返回一个没有重复项的序列(如果类型覆盖了类似字符串的GetHashCode
和Equals
)。 如果您想从列表中删除重复项,则必须将其重新分配给列表变量:oList = oList.Distinct().ToList()
。ToList
创建一个带有唯一字符串的新列表。 - Tim Schmelter