You could also define ordering methods on your objects for the more complex cases:
Person>>preceedsByLastNameAndAge: otherPerson
^(self lastName = otherPerson lastName) ifTrue: [ self age <= otherPerson age ] ifFalse: [ self lastName < otherPerson lastName ]
...and the sort block would be:
[ :a :b | a preceedsByLastNameAndAge: otherPerson ]
- Stephen
-----Original Message----- From: Hans-Martin Mosner [mailto:hm.mosner@cityweb.de] Sent: Wednesday, May 02, 2001 2:59 PM To: squeak@cs.uiuc.edu Subject: Re: SortedCollection
Just give it a sort block that compares with > or >= instead of <=
In Smalltalk, SortedCollections compare their elements using a block, which defaults to [:a :b | a <= b]. For every two elements x,y of the collection, x comes before y when sortBlock value:x value: y returns true. So by using a sortBlock of [:a :b | a >= b] you sort in descending order.
There are various ways of setting the sortBlock of a SortedCollection:
- You can give a new sortBlock to an existing collection: someSortedCollection sortBlock: [:a :b | a >= b].
- You can create a SortedCollection with the right sortBlock, for adding
elemtns later: someSortedCollection := SortedCollection sortBlock: [:a :b | a >= b].
- You can make a SortedCollection from an existing collection of
objects: someSortedCollection := someArbitraryCollection asSortedCollection: [:a :b | a >= b]
This should get you started... :-)
More sorting tips:
If you want to sort complex objects by some attribute, that's very easy, too: [:a :b | a firstName <= b firstName] will sort ascending to firstName. Of course all elements of the collection must understand that message.
You can also sort by more than one attribute: [:a :b | a lastName = b lastName ifTrue: [a age <= b age] ifFalse: [a lastName < b lastName]] will sort by lastName first, and within equal lastNames, will sort by age. That gets pretty complicated for more than two attributes, though...
Cheers, Hans-Martin
Jeff Shipman wrote:
I would like to do a descending sort on a SortedCollection. How could I do this?
Jeff "Shippy" Shipman E-Mail: shippy@nmt.edu Computer Science Major ICQ: 1786493 New Mexico Institute of Mining and Technology Homepage: http://www.nmt.edu/~shippy
"Stephen" == Stephen Pair spair@advantive.com writes:
Stephen> You could also define ordering methods on your objects for the more complex Stephen> cases:
Person> preceedsByLastNameAndAge: otherPerson
Stephen> ^(self lastName = otherPerson lastName) ifTrue: [ Stephen> self age <= otherPerson age Stephen> ] ifFalse: [ Stephen> self lastName < otherPerson lastName Stephen> ]
Stephen> ...and the sort block would be:
Stephen> [ :a :b | a preceedsByLastNameAndAge: otherPerson ]
Stephen> - Stephen
Although so as not to freak out the English Majors, you'd probably spell precedes correctly. :)
squeak-dev@lists.squeakfoundation.org