Results 1 to 3 of 3

Thread: [02/03] Sort Array

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Dec 2003
    Posts
    4,787

    [02/03] Sort Array

    Hi,

    I Have a class which contains various data fields, I have an array of this class, InvoiceData(30). How can I sort the array based on a specific field in the class? eg quantity.

    Thanks

  2. #2
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: [02/03] Sort Array

    I think you could do it using a comparer class:

    VB.NET Code:
    1. Class InvoiceQuantityComparer : Implements IComparer
    2.   Public Function Compare(a As Object, b As Object) Implements IComparer.Compare
    3.     If (TypeOf a Is Invoice AndAlso TypeOf b Is Invoice) Then
    4.       Dim invoice_a As Invoice = DirectCast(a, Invoice)
    5.       Dim invoice_b As Invoice = DirectCast(b, Invoice)
    6.  
    7.       Return invoice_a.Quantity.CompareTo(invoice_b.Quantity)
    8.     Else
    9.       Throw New ArgumentException()
    10.     End If
    11.   End Function
    12. End Class
    13.  
    14. ' Usage:
    15. Array.Sort(InvoiceData, New InvoiceQuantityComparer())

    Don't have VB.NET on here, or I'd test that first.

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [02/03] Sort Array

    That's a more general solution. A narrower one would be to implement the IComparable interface on the class. This gives you a standard means of ordering two objects, and allows you to then use Array.Sort.

    Here's an example I pulled from one of my projects. The types are unimportant, other than that they are custom classes:

    vb Code:
    1. 'Used by the IComparable interface
    2.     Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
    3.         If TypeOf obj Is Genome Then
    4.             Dim temp As Genome = CType(obj, Genome)
    5.  
    6.             Return myQuality.CompareTo(temp.myQuality)
    7.         End If
    8.  
    9.     End Function

    EDIT: I ought to mention that when you add the IComparable interface to the class declaration, you get the stubbed out CompareTo() function, and the code I have in that function I just took from MSDN and altered to suit my situation. Obviously, you could expand on the IF statement to compare objects of many different types, such that you could sort an array of your class, strings, and a few integers.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width