簡體   English   中英

我們如何通過pharo中的特定鍵對數組中的字典進行排序?

[英]How can we sort dictionaries in an array by a specific key in pharo?

我有一個包含幾個字典的數組。 如何使用每本詞典具有相同年齡的鍵對它們進行排序?

an Array((a Dictionary('age'->'20' 'ID'->1254))(a Dictionary('age'->'35' 'ID'->1350))(a Dictionary('age'->'42' 'ID'->1425)))

您可以通過提供一個比較器塊進行排序。 該塊接受兩個參數(數組中的兩個元素),並期望返回布爾值。

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') ].
  • 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' ))"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM