Sorting lists by fields
BlitzMax Forums/BlitzMax Beginners Area/Sorting lists by fields
| ||
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. |
| ||
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. |
| ||
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. |
| ||
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). |
| ||
Thanks to both of you. CompareFunc was something I had previously had no knowledge of, and seems to be the key in all this. |