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:
00508886
Views:
23
This message has been marked as the solution to the initial question of the thread.
>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
Éric Moreau, MCPD, Visual Developer - Visual Basic MVP
Conseiller Principal / Senior Consultant
Moer inc.
http://www.emoreau.com
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform