Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SortedList Desc Order

Tags:

c#

I am using SortedList to arrange arraylist records dynamically in sort order by datecolumn, but by default it is sorting in ascending order. I have been trying to get order in descending order but not able to get it.

like image 746
Pardha Avatar asked Oct 19 '11 02:10

Pardha


People also ask

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.

How do I reverse a sorted list in C#?

To reverse the sort order, you may invoke the List. Reverse() method on the sorted list. That's all about sorting lists in descending order in C#.

What is SortedList?

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

How do you sort a set in descending order in Python?

sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.


2 Answers

Swapping y for x should do when comparing

class DescComparer<T> : IComparer<T> {     public int Compare(T x, T y)     {         if(x == null) return -1;         if(y == null) return 1;         return Comparer<T>.Default.Compare(y, x);     } } 

and then this

var list = new SortedList<DateTime, string>(new DescComparer<DateTime>()); 
like image 160
UBCoder Avatar answered Sep 23 '22 21:09

UBCoder


There is no way to instruct the SortedList to do sorting in descended order. You have to provide your own Comparer like this

    class DescendedDateComparer : IComparer<DateTime>     {         public int Compare(DateTime x, DateTime y)         {             // use the default comparer to do the original comparison for datetimes             int ascendingResult = Comparer<DateTime>.Default.Compare(x, y);              // turn the result around             return 0 - ascendingResult;         }     }      static void Main(string[] args)     {         SortedList<DateTime, string> test = new SortedList<DateTime, string>(new DescendedDateComparer());     } 
like image 40
Polity Avatar answered Sep 23 '22 21:09

Polity