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
Printable View
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
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.:blush:
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.