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.
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.
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#.
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.
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.
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>());
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()); }
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