我们如何通过pharo中的特定键对数组中的字典进行排序?

lud*_*udo 0 smalltalk pharo pharo-5

我有一个包含几个字典的数组.如何使用每个字典都具有年龄的密钥对它们进行排序?

an Array((a Dictionary('age'->'20' 'ID'->1254))(a Dictionary('age'->'35' 'ID'->1350))(a Dictionary('age'->'42' 'ID'->1425)))
Run Code Online (Sandbox Code Playgroud)

Pet*_*nak 5

您可以通过提供比较器块进行排序; 该块接受两个参数(数组中的两个元素),并期望返回布尔值.

data := { 
    { 'age' -> '20'. 'ID' -> 1254 } asDictionary.
    { 'age' -> '35'. 'ID' -> 1350 } asDictionary.
    { 'age' -> '42'. 'ID' -> 1425 } asDictionary
}.
sorted := data sorted: [ :a :b | (a at: 'age') > (b at: 'age') ].
Run Code Online (Sandbox Code Playgroud)
  • sorted: 将返回已排序的集合而不更改接收器
  • sort: 将就地进行排序并返回自己

您还可以使用asSortedCollection:哪个将创建一个始终支持排序不变的新集合.

sc := data asSortedCollection: [ :a :b | (a at: 'age') > (b at: 'age') ].

"automatically inserted between age 42 and 35"
sc add: {'age' -> '39'. 'ID' -> 1500} asDictionary.
sc "a SortedCollection(a Dictionary('ID'->1425 'age'->'42' ) a Dictionary('ID'->1500 'age'->'39' ) a Dictionary('ID'->1350 'age'->'35' ) a Dictionary('ID'->1254 'age'->'20' ))"
Run Code Online (Sandbox Code Playgroud)