Mykhalik
Mykhalik

Reputation: 244

Sorting SortedList in descending order C#

I have

SortedList<string, object> testIds = new SortedList<string, object>();

And I neet it sort in descending order. I used for sorting next construction:

testIds.ToList().Sort(delegate(KeyValuePair<string, object>x, KeyValuePair<string, object>y)
{
     return x.Key.CompareTo(y.Key)*-1;
});

But it did not help me.Can you give me some advice how to solve this problem?

Upvotes: 3

Views: 6938

Answers (3)

i100
i100

Reputation: 4666

Just use Reverse. Let's suppose you have a orderedlist OrigOrderedList, then

SortedList<string, object> testIds = OrigOrderedList.Reverse() // should do the work

static void Main(string[] args)
    {
      SortedList<string, object> test1 = new SortedList<string, object>();
      test1.Add("a", "A");
      test1.Add("b", "B");
      test1.Add("c", "C");
      Console.WriteLine(String.Join(", ", test1.Select(x => x.Key)));
      Console.WriteLine(String.Join(", ", test1.Reverse().Select(x => x.Key)));
    }

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Although SortedList<K,V> sorts in ascending order by default, it provides a constructor that takes a custom IComparer<K> that lets you switch the order to whatever you need.

Implement IComparer<string> that inverts the result of the regular comparison, and give it to the constructor of SortedList<K,V>:

class ReverseComparer : IComparer<string> {
    public int Compare(string x, string y) {
        return -x.CompareTo(y);
    }
}

var testIds = new SortedList<string,object>(new ReverseComparer());

You can write the same thing in a single line, without making a named class for it:

var testIds = new SortedList<string,object>(
    // Note how the negation is replaced with reversing the order of comparison
    Comparer<string>.Create((x, y) => y.CompareTo(x))
);

Upvotes: 11

dcastro
dcastro

Reputation: 68750

As pointed out by dasblinkenlight, you should use the constructor overload that takes an IComparer<T>.

However, if this is a one time thing, you're better off using Comparer<T>.Create, instead of creating a whole new class just for this.

var comparer = Comparer<string>.Create((x, y) => y.CompareTo(x)); 

var testIds = new SortedList<string,object>(comparer);

Also, when comparing items in reverse order, the convention is to compare y with x, instead of comparing x with y and inverting the result.

Upvotes: 8

Related Questions