Sorting lists by fields

BlitzMax Forums/BlitzMax Beginners Area/Sorting lists by fields

fetcher(Posted 2009) [#1]
The code below takes a list of 3 objects and sorts them by their name field. This was done by giving TPerson an overriding Compare method. The problem now is that I can only sort the list by the one field (name).



How would I be able to sort by name, age or weight? Can I send the field I want to sort by to the Compare Method? I was only able to figure out this much by searching through the forums. There are several references to being able to sort by multiple fields, but no code examples or detailed explanations.


N(Posted 2009) [#2]
Method Sort( ascending:Int = True, compareFunc( o1:Object, o2:Object ) = CompareObjects )


Use the compareFunc argument of TList#Sort. Sorting by more than one field at the same time is another matter, however, and it's entirely up to you to implement that using your own logic.


jsp(Posted 2009) [#3]
You can use a global variable inside your type to indicate the field you want to sort.
Set that variable whenever you like to change the sortstyle.
Then have a Select Case inside your compare function.




N(Posted 2009) [#4]
That's really overcomplicating it, I think. Not to mention your line, "If name > obj.name" would be much better handled as simply Return name.Compare(other.name).


fetcher(Posted 2009) [#5]
Thanks to both of you. CompareFunc was something I had previously had no knowledge of, and seems to be the key in all this.