Skip to main content

orderBy

For any types T and K,

orderBy(collection: Bag<T>,  keySelector: T -> K) : List<T>

Sorts a collection by applying a key selector function to each element and ordering by the resulting keys.

  • The collection is sorted in ascending order based on the values returned by keySelector.
  • For descending order, consider using the order by clause with desc modifier in a comprehension, or negate numeric keys.
  • See comparisons for more detail on the order of values.
  • Note that this method accepts both Lists and Bags ─since Lists subtype Bags

Example

Sorting Devices by Name

getName(device) = device.name;
orderBy(network.devices, getName);

This is equivalent to the more verbose, albeit more flexible, comprehension:

foreach device in network.devices
let name = device.name
select device
order by name ascending

Notes

  • For sorting by multiple keys or for descending order, consider using the order by clause in a comprehension instead.
  • Elements with equal keys maintain their relative order from the original list (stable sort).

See Also

Guides

Functions

  • limit - Limit the number of elements in a list
  • max - Get the maximum element
  • min - Get the minimum element
  • maxBy - Get element with maximum key
  • minBy - Get element with minimum key