|
-
Jul 2nd, 2007, 07:55 AM
#1
Thread Starter
PowerPoster
[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
-
Jul 2nd, 2007, 08:05 AM
#2
Re: [02/03] Sort Array
I think you could do it using a comparer class:
VB.NET Code:
Class InvoiceQuantityComparer : Implements IComparer
Public Function Compare(a As Object, b As Object) Implements IComparer.Compare
If (TypeOf a Is Invoice AndAlso TypeOf b Is Invoice) Then
Dim invoice_a As Invoice = DirectCast(a, Invoice)
Dim invoice_b As Invoice = DirectCast(b, Invoice)
Return invoice_a.Quantity.CompareTo(invoice_b.Quantity)
Else
Throw New ArgumentException()
End If
End Function
End Class
' Usage:
Array.Sort(InvoiceData, New InvoiceQuantityComparer())
Don't have VB.NET on here, or I'd test that first.
-
Jul 2nd, 2007, 09:26 AM
#3
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:
'Used by the IComparable interface
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
If TypeOf obj Is Genome Then
Dim temp As Genome = CType(obj, Genome)
Return myQuality.CompareTo(temp.myQuality)
End If
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|