Sorting Structures

kumarangopi

Member
Joined
Apr 12, 2008
Messages
14
Programming Experience
Beginner
I have declared a structure

Structure student
Dim sname As String
Dim sage As Integer
End Structure

1.I want to sort it on sage field
2.I want to find maximum sage in the structure and display the records matching maximum sage.

Any ideas?Thanks in advance
 
Class or Structure is irrelevant here.
To define default sorting implement IComparable(Of T) in your type. Sample:
VB.NET:
Structure student
    Implements IComparable(Of student) 'pressing (Enter) here generates the interface members

    Dim name As String
    Dim age As Integer

    Public Function CompareTo(ByVal other As student) As Integer Implements System.IComparable(Of student).CompareTo
        Return Me.age.CompareTo(other.age)
    End Function
End Structure
This would sort with a call to
VB.NET:
Array.Sort(studentsArray) 
'or 
studentsList.Sort()
------------------------------------------
To setup different external sorts write a class that implements IComparer(Of T). Sample:
VB.NET:
Class sorter
    Implements IComparer(Of student) 'pressing (Enter) here generates the interface members

    Public Function Compare(ByVal x As student, ByVal y As student) As Integer Implements System.Collections.Generic.IComparer(Of student).Compare
        Return x.age.CompareTo(y.age)
    End Function
End Class
This would sort with a similar call, only you specify as parameter an instance of this sorter class:
VB.NET:
Array.Sort(studentsArray, New sorter) 
'or 
studentsList.Sort(New sorter)
------------------------------------------
It is also possible to use the Comparison(Of T) delegate, here you just write the function:
VB.NET:
Public Function CompareAge(ByVal x As student, ByVal y As student) As Integer
    Return x.age.CompareTo(y.age)
End Function
This would sort with a similar call, only you specify as parameter an instance of the Comparison delegate with AddressOf:
VB.NET:
Array.Sort(studentsArray, AddressOf CompareAge) 
'or 
studentsList.Sort(AddressOf CompareAge)

This is short for:
VB.NET:
Array.Sort(studentsArray, New Comparison(Of student)(AddressOf CompareAge))
 
Back
Top