Sortwith descending using downto?

I am sorting the array theSelection() based on a custom class with one of the properties being theHSVH (an integer). This works fine ascending, but descending using downto creates a mess and I don’t understand why:

Var theSort() As Integer
var i as Integer

if Preferences.SortDirection="Ascending" then
  For i = 0 To theSelection.LastRowIndex
    theSort.Add(theSelection(i).theHSVH)
  Next
else
  For i  = theSelection.LastRowIndex DownTo 0
    theSort.Add(theSelection(i).theHSVH)
  Next
end if

theSort.SortWith(theSelection)

Any suggestions what I am doing wrong? Thanks!

If I’m understanding this right, you’re adding integers to the array, just adding them in a different order depending on ascending vs. descending. Then you’re sorting them. You should end up with identical arrays because they’ve been sorted.

What you can do is take your ascending sort and access it in reverse order:

Var names() As String = Array("Jim", "Bob", "Jane")
names.Sort

// names = "Bob", "Jane", "Jim"

// For a descending sort, access the array in reverse order
Var reverseNames() As String
For i As Integer = names.LastRowIndex DownTo 0
  reverseNames.Add(names(i))
Next

// reverseNames = "Jim", "Jane", "Bob"

When adding code to a post, please add it, then select it all, then click the </> button in the toolbar.

Thanks for the tip, done!

I would use a delegate method to sort the objects. Have a look at https://blog.xojo.com/2016/03/09/easily-sorting-arrays-of-classes/ Paul’s blog post.

Thanks Wayne, this works great!