tobjectlist_sort.bmx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. SuperStrict
  2. Framework Brl.ObjectList
  3. Import Brl.StandardIO
  4. ' create an object list to hold some objects
  5. Local list:TObjectList = New TObjectList
  6. ' add some string objects to the end of the list
  7. list.AddLast("short")
  8. list.AddLast("longer")
  9. list.AddLast("the longest")
  10. ' DEFAULT SORT
  11. ' sort them (in this case this leads to an alphabetic sort)
  12. ' second parameter sets sort to ascending or not
  13. list.Sort(True)
  14. ' enumerate all the strings in the list
  15. For Local a:String = EachIn list
  16. Print a
  17. Next
  18. ' outputs:
  19. ' longer
  20. ' short
  21. ' the longest
  22. ' CUSTOM SORT
  23. ' define a custom compare function
  24. Function MyCompare:Int( o1:Object, o2:Object )
  25. If Len(String(o1)) < Len(String(o2)) Then
  26. Return -1 ' o1 before o2
  27. ElseIf Len(String(o1)) > Len(String(o2)) Then
  28. Return 1 ' o1 after o2
  29. Else
  30. Return 0 ' equal
  31. EndIf
  32. End Function
  33. ' sort them with a custom compare function
  34. list.Sort(True, MyCompare)
  35. ' enumerate all the strings in the list
  36. For Local a:String = EachIn list
  37. Print a
  38. Next
  39. ' outputs:
  40. ' short
  41. ' longer
  42. ' the longest