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 byclause withdescmodifier in a comprehension, or negate numeric keys. - See comparisons for more detail on the order of values.
- Note that this method accepts both
ListsandBags─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 byclause in a comprehension instead. - Elements with equal keys maintain their relative order from the original list (stable sort).
See Also
Guides
- Collections - Comprehensive guide on Lists, Bags, and ordering
- Comprehensions - Using order by clause