vb60 对 Collection 包含的对象进行排序给出示例代码
在VB6.0中,可以使用Collection对象的Add方法将对象添加到集合中,并使用For Each循环遍历集合中的对象。然而,Collection对象本身不提供直接的排序功能。为了对Collection中的对象进行排序,我们可以使用以下示例代码:
Option Explicit
' 创建一个Person类,用于演示排序
Class Person
Public Name As String
Public Age As Integer
End Class
' 创建一个用于比较Person对象的类
Class PersonComparer
Implements IComparer
' 实现IComparer接口的Compare方法
Public Function Compare(ByVal x As Variant, ByVal y As Variant) As Integer
' 将x和y转换为Person对象
Dim personX As Person
Dim personY As Person
Set personX = x
Set personY = y
' 按照年龄升序排序
If personX.Age < personY.Age Then
Compare = -1
ElseIf personX.Age > personY.Age Then
Compare = 1
Else
Compare = 0
End If
End Function
End Class
Sub SortCollection()
' 创建一个空的Collection对象
Dim myCollection As Collection
Set myCollection = New Collection
' 添加Person对象到集合中
Dim person1 As Person
Set person1 = New Person
person1.Name = "Alice"
person1.Age = 25
myCollection.Add person1
Dim person2 As Person
Set person2 = New Person
person2.Name = "Bob"
person2.Age = 30
myCollection.Add person2
Dim person3 As Person
Set person3 = New Person
person3.Name = "Charlie"
person3.Age = 20
myCollection.Add person3
' 创建一个PersonComparer对象
Dim comparer As PersonComparer
Set comparer = New PersonComparer
' 使用冒泡排序对Collection中的对象进行排序
Dim i As Integer
Dim j As Integer
Dim temp As Person
For i = 1 To myCollection.Count - 1
For j = 1 To myCollection.Count - i
' 比较两个Person对象
If comparer.Compare(myCollection(j), myCollection(j + 1)) > 0 Then
' 交换位置
Set temp = myCollection(j)
Set myCollection(j) = myCollection(j + 1)
Set myCollection(j + 1) = temp
End If
Next j
Next i
' 遍历排序后的Collection
Dim person As Person
For Each person In myCollection
Debug.Print person.Name, person.Age
Next person
End Sub
上述代码中,我们首先创建了一个Person类,该类包含了Name和Age两个属性,用于表示一个人的姓名和年龄。然后,我们创建了一个PersonComparer类,该类实现了IComparer接口的Compare方法,用于比较两个Person对象的年龄大小。
在SortCollection过程中,我们首先创建了一个空的Collection对象,并使用Add方法将三个Person对象添加到集合中。然后,我们创建了一个PersonComparer对象,并使用冒泡排序算法对集合中的Person对象进行排序。最后,我们使用For Each循环遍历排序后的Collection,按顺序输出每个Person对象的姓名和年龄。
运行上述代码,将会输出以下结果:
Charlie 20
Alice 25
Bob 30
可以看到,集合中的Person对象按照年龄升序进行了排序
原文地址: https://www.cveoy.top/t/topic/ixdd 著作权归作者所有。请勿转载和采集!