How do you sort a Structure Array?

BlakeMcKenna

Active member
Joined
Oct 27, 2008
Messages
38
Programming Experience
10+
I'm using VB.Net 2005. I have created a Structure Array that contains 7 fields. I am trying to figure out how to sort this thing and have no idea. I've been reading up on the Array.Sort function and I'm bombarded with Overloads. I just don't know how to set up the statement. Below is my code:

VB.NET:
    [COLOR="Blue"]'Structure Definition defined in a Module[/COLOR]
    Private Structure CSVFile
        Dim siteID As Integer
        Dim tankID As Integer
        Dim dispenser As Integer
        Dim prodID As String
        Dim invDate As String
        Dim quantity As String
        Dim date2 As String
    End Structure
    Private arrOutFile() As CSVFile

    [COLOR="blue"]'This code is in a Sub-Procedure[/COLOR]

    [COLOR="blue"]'I load the structure array with values[/COLOR]    
    ReDim Preserve arrOutFile(idx)

    arrOutFile(idx).siteID = intSiteID
    arrOutFile(idx).tankID = intTankID
    arrOutFile(idx).dispenser = row(2)
    arrOutFile(idx).prodID = strProdID
    arrOutFile(idx).invDate = strDate1
    arrOutFile(idx).quantity = strQuantity
    arrOutFile(idx).date2 = strDate2

    idx += 1

    [COLOR="blue"]'When the array has finished loading, I try to sort it based on the 1st 
    'three fields in the structure (which I don't know how to setup as a key)[/COLOR]

    If arrOutFile Is Nothing Then
    Else
        [COLOR="Red"]Array.Sort(arrOutFile)[/COLOR]
    End If

The RED Highlighted line is where I'm stuck at. I keep getting an error saying
"At least one object must implement IComparable."

Please help,

Thanks
 
JohnH,

Your post makes a little more sense to me, the last example specifically. With that in mind, I need to return 3 values (which would be the 3 fields I'm sorting by) in the function.

VB.NET:
Public Function CompareAge(ByVal x As student, ByVal y As student) As Integer
    Return x.siteID.CompareTo(y.siteID)
    Return x.tankID.CompareTo(y.tankID)
    Return x.dispenser.CompareTo(y.dispenser)
End Function

How do I do this?

Thanks,
 
Have a closer look at the CompareTo function and the possible values it returns.

The return value is 0 if the values are equals. If they do for one property it makes sense to compare another, else the value of the first comparison will determine the sort order and can be returned. Sample:
VB.NET:
Dim ret As Integer = x.A.CompareTo(y.A)
If ret <> 0 Then Return ret 'a sort order is determined
ret = x.B.CompareTo(y.B)
If ret <> 0 Then Return ret
Return x.C.CompareTo(y.C) 'last compare, return also 0/equal
 
Back
Top