Function keepOnlyDuplicates(ByRef list1 As List(Of Integer), ByRef list2 As List(Of Integer)) As List(Of Integer)
Dim returnList As New List(Of Integer)
For Each i As Integer In list1
For Each j As Integer In list2
If i = j Then
returnList.Add(i)
Exit For
End If
Next
Next
Return returnList
End Function
我使这个函数从另外两个中创建一个新的整数列表,其中只包含两者中的整数(各个列表没有重复)。
有没有办法修改此功能,以便它接受任何类型的列表并返回相应类型的列表而不会有太多麻烦?如果它真的很复杂,我可以轻松地为其他类型创建另一个函数。但是,如果只是要调用什么类型的问题那么我该怎么做呢?
感谢。
答案 0 :(得分:3)
Function keepOnlyDuplicates(Of t As IComparable)(ByRef list1 As List(Of t), ByRef list2 As List(Of t)) As List(Of t)
Dim returnList As New List(Of t)
For Each i As t In list1
For Each j As t In list2
If i.CompareTo(j) = 0 Then
returnList.Add(i)
Exit For
End If
Next
Next
Return returnList
End Function
如果t将是您自己的类型,那么:
//用于完全比较添加您自己的类型Implements IComparable
或者这样做。 如果你只检查平等 将功能更改为
Function keepOnlyDuplicates(Of t)(ByRef list1 As List(Of t), ByRef list2 As List(Of t)) As List(Of t)
在这种情况下,对于你自己的类型,只需覆盖equal()。 将条件改为
If i.Equals(True) = True Then .