Sorting any field
BlitzMax Forums/BlitzMax Beginners Area/Sorting any field
| ||
I realise you can use compare method to sort on a particular field. However, I can't work out how to sort on ANY field. For example, if I have a type with X and Y fields how can I use sortlist with compare override but specify which field out of X and Y I want sorted? |
| ||
Type Bob Field X,Y Field SortUsingY Method Compare(other:Object) If Bob(other) If SortUsingY Return Sgn(Y - Bob(other).Y) Else Return Sgn(X - Bob(other).X) EndIf EndIf Return -1 EndMethod EndTypeOr something like that. It's probably better to have a global variable controlling which parameter to use, instead of one for each type instance. |
| ||
I went with the global variable as a quick solution. What if the compare is against either an int or a string field? What would the method return? <EDIT> Ignore me. I'm being a muppet. |
| ||
Lets say I have a List of this Type....Type Unit Field X:Float,Y:Float Field Number:Int Method New() Number=Rand(1000) ListAddLast UnitList,Self End Method End Type How Can I Use Sort to Sort this list Using the Number Field. I want to go from Low to High. Regards, Eric |
| ||
Type Unit Global unitlist:Tlist=CreateList() Field X:Float,Y:Float Field Number:Int Method New() Number=Rand(1000) ListAddLast UnitList,Self End Method Method compare(myobject:Object) s:Unit = Unit(myobject) If Not s Then Return 1 Return number - s.number End Method End Type SeedRnd MilliSecs() For x = 1 To 100 my:Unit = New unit Next SortList unit.unitlist ' Check to see if it is sorted correctly For s:unit = EachIn unit.unitlist Print s.number Next |