Can I sort a structured array using Array.Sort?
Author Message
Can I sort a structured array using Array.Sort?

Hi,
Can I sort the array (arr) below according to the
field 'int' by using Array.Sort.

Private Structure strArr
Public int As Int16
Public str As String
End Structure

Dim arr(3) As strArr

Thanks,

Mon, 31 Jan 2005 22:38:25 GMT
Can I sort a structured array using Array.Sort?
Yes, your structure must implement IComparable interface

example

Private Structure strArr : Implements IComparable
Public int As Int16
Public str As String
Public Function Compare(ByVal x As Object) As Integer Implements
IComparable.CompareTo
Dim oY As strArr = CType(x, strArr)
If Me.int > oY.int Then Return 1
If Me.int < oY.int Then Return -1
If Me.int = oY.int Then Return 0
End Function
End Structure

HTH

--
UGIdotNET - http://www.ugidotnet.org

Tue, 01 Feb 2005 00:27:02 GMT
Can I sort a structured array using Array.Sort?

Quote:
> Can I sort the array (arr) below according to the
> field 'int' by using Array.Sort.

>     Private Structure strArr
>         Public int As Int16
>         Public str As String
>     End Structure

>     Dim arr(3) As strArr

Private Structure strArr
Implements IComparable

Public int As Int16
Public str As String

Public Function CompareTo(ByVal obj As Object) As Integer _
Implements System.IComparable.CompareTo

Return Me.int.CompareTo(DirectCast(obj, strArr).int)

End Function

End Structure

Test:
Dim a As strArr()
ReDim a(5)
a(0).int = 2
a(1).int = 5
a(2).int = 6
a(3).int = 1
a(4).int = 4
a(5).int = 3

Array.Sort(a)

Armin

Mon, 31 Jan 2005 23:13:34 GMT

 Page 1 of 1 [ 3 post ]

Relevant Pages