Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an enumerable in descending order

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.

like image 630
Tom Lehman Avatar asked Jan 26 '10 20:01

Tom Lehman


People also ask

How to sort in descending order in LINQ?

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.

How do you sort the generic SortedList in the descending order?

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.


1 Answers

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).

like image 116
bryantsai Avatar answered Sep 19 '22 11:09

bryantsai