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

--
Corrado Cavalli
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  
 
 [ 3 post ] 

 Relevant Pages 

1. Can I sort a structured array using Array.Sort? USING C#

2. Sorting an array of type Structure

3. Sorting array of structures

4. array sorting, structures

5. Looking for an algorithm for building an index-array for sorting an array or database table

6. VB6: How to initialize a variable as a array structure / structure (type) array (see example)

7. sort a user defined array using 2 keys?

8. Sorting Collection directly without using an Array

9. Sort order - Edit Filter Sort or Quick Sort

10. Passing an array (or array of a structure) from VB to VC++

11. Can't sort Outlook Personal Folder using Items.Sort

12. Array Sorting code in VB

 

 
Powered by phpBB® Forum Software