SortWith Misunderstanding

Clearly my understanding of how SortWith works is flawed.

I have two arrays:

 fileList() as String
 fileSize() as Integer

I want to sort the fileList array alphabetically, so I use:


Now I would like to sort the fileSize array in the same order the sorted fileList array is in, so I try:


This does’t work, however.
Can someone help clear up my understanding of how SortWith is supposed to work?


fileSize.SortWith (fileList)


Here’s the documentation for SortWith so you don’t have to guess how things work:

If the two arrays are related to each other, you need to SortWith every time.

Yes, that’s where I started (naturally).
Unfortunately I came away with the understanding that what I have shown (above) would do what I’m wanting… and it does not. I read the docs and evidently do not understand them correctly.

I tried that as well. Also doesn’t sort the fileSize array in the same order as the fileList array.

So a key takeaway is that the base array is the one doing the sort. Both arrays are being sorted every time.

arsNames.SortWith(ariSizes) will sort the sizes array the same way the names array gets sorted.

You must always keep these in sync. The first thing your original post does is separate the association between the names and the sizes by sorting the names array by itself.

1 Like


Ah… I get it now.
Once the association is made the associated arrays will then be sorted in the order of the base array. So I make the associations between whatever arrays need to be connected and then sort the original array, and the rest will follow.

Thank you Tim

1 Like

I thought the same thing that the OP did. I get it now, but that is really unintuitive. In most cases you would want a sorted Index of the original array so that you can then refer back to the original array by index. It doesn’t do any good to have a sorted index if the array it was based off of is now also sorted. I can work around it, but that is an odd implementation. So much to love about Xojo, but this one doesn’t make the list.

I can’t say as I agree. I have two arrays where the item with index j in one array belongs with the item with index j in the other array. I want to be able to sort both according to some criterion that relates to one on the arrays, and then still have the association between items in the two arrays with the same index.


I agree with Tim, think of it as:

arraySortThisArray.SortWith( arrayKeepMeInSync, arrayAndMe, arrayAndMeToo )

All the arrays are sorted, but they are sorted into the order of the first one.

You can also think of it as a table where each array is a column. Sorting the table by one of the columns, is effectively what this is providing.