Pardha
Pardha

Reputation: 415

SortedList Desc Order

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.

Upvotes: 35

Views: 31681

Answers (6)

Jaydeep Shil
Jaydeep Shil

Reputation: 1959

while adding the value if we multiply with -1 we can achieve descending order.

Example - Lets say we want to store 10 and 3 but list should be sorted in desc without any extra operation (Reverse, IComparer), we can multiply each no with -1 before adding as key and the original value as value, like I am doing below

SortedList<int, int> pairs = new SortedList<int, int>();
pairs.Add(-10, 10);
pairs.Add(-3, 3);

Now the list having the items sorted in desc order as 10 will be at the top.

enter image description here

Upvotes: 1

Chris Moschini
Chris Moschini

Reputation: 37957

Just swap a and b in the Default Comparer, which is accessible through these convenience classes and properties:

var desc = Comparer<DateTime>.Create((a, b) => Comparer<DateTime>.Default.Compare(b, a));

var sortedList = new SortedList<DateTime, T>(desc);

Upvotes: 2

Scott Kim
Scott Kim

Reputation: 31

Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));

Upvotes: 3

UBCoder
UBCoder

Reputation: 689

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>());

Upvotes: 46

Polity
Polity

Reputation: 15130

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

Upvotes: 31

Jakob Gade
Jakob Gade

Reputation: 12419

You can just use Reverse() to sort the SortedList in descending order:

var list = new SortedList<DateTime, string>();

list.Add(new DateTime(2000, 1, 2), "Third");
list.Add(new DateTime(2001, 1, 1), "Second");
list.Add(new DateTime(2010, 1, 1), "FIRST!");
list.Add(new DateTime(2000, 1, 1), "Last...");

var desc = list.Reverse();

foreach (var item in desc)
{
    Console.WriteLine(item);
}

Upvotes: 21

Related Questions