Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Sorting collection object
Message
General information
Forum:
Visual Basic
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
00508828
Message ID:
00508921
Views:
25
It was just that I was looking for a better way than to loop through the collection each time I need to add a new object but I guess not.

Thanks for the code though.

>>I have a collection object of numerous class object. For example, collection of "objInvoice" in a collection object named "objInvoices".
>>
>>My question is, what's the "best" way to sort the objects within the collection? For example, if I have collection of "objInvoice" and want to sort by "Total amount" so that objects are stored in the collection in sorted order.
>
>You will need to use the After (or Before) parameter on the Add method calling. This parameter allow you to set the actual position when inserting an item in a collection. The thing is that you need to give the ordinal position in this parameter. One way of doing it is to loop the collection:
>
>
Option Explicit
>
>Private mcolX As Collection
>
>Private Sub Command1_Click()
>Dim objInvoice As clsInvoice
>
>    Set mcolX = New Collection
>
>    Set objInvoice = New clsInvoice
>    objInvoice.InvoiceNumber = "i010"
>    objInvoice.Amount = 10
>    Call AddItemToColl(objInvoice)
>
>    Set objInvoice = New clsInvoice
>    objInvoice.InvoiceNumber = "i020"
>    objInvoice.Amount = 20
>    Call AddItemToColl(objInvoice)
>
>    Set objInvoice = New clsInvoice
>    objInvoice.InvoiceNumber = "i001"
>    objInvoice.Amount = 1
>    Call AddItemToColl(objInvoice)
>
>    Set objInvoice = New clsInvoice
>    objInvoice.InvoiceNumber = "i025"
>    objInvoice.Amount = 25
>    Call AddItemToColl(objInvoice)
>
>    Call DisplayColl
>End Sub
>
>Private Sub AddItemToColl(ByVal pobjInv As clsInvoice)
>Dim intPos As Integer
>Dim x As clsInvoice
>
>    intPos = 0
>    For Each x In mcolX
>        If x.Amount > pobjInv.Amount Then
>            Exit For
>        End If
>        intPos = intPos + 1
>    Next
>    If mcolX.Count = 0 Then
>        mcolX.Add pobjInv
>    ElseIf intPos = 0 Then
>        mcolX.Add pobjInv, , 1
>    Else
>        mcolX.Add pobjInv, , , intPos
>    End If
>End Sub
>
>Private Sub DisplayColl()
>Dim x As clsInvoice
>
>    For Each x In mcolX
>        MsgBox x.InvoiceNumber & ": " & x.Amount
>    Next
>End Sub
It's "my" world. You're just living in it.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform