What's the best way to sort an Enumerable
in descending order?
I've been doing @array.sort.reverse
or @array.sort_by{|song| song.title }.reverse
I suppose I could do something like @array.sort{|a, b| b.title <=> a.title}
, but I find this hard to read and verbose.
OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
Use Comparer<T> to sort the SortedList in descending order instead of creating a separate class. Thus, you can create an instance of SortedList<TKey, TValue> to sort the collection in descending order.
The performance of Array.reverse
is not very bad. What costs you by using @array.sort.reverse
is an extra array duplication plus the reverse (n/2 element switches). So yes, I think that should be acceptable if you think it's read clearer.
See its source for details. And also, I think using @array.sort.reverse
does provide 'slightly' better readability (but it's not very hard to read any way).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With