How to make a sortedlist sort reversely? Do I have to customize a IComparer?

colinfang picture colinfang · Jun 1, 2011 · Viewed 7k times · Source

In a sortedlist queue, queue.value[0] gives the corresponding value of a min key. what if i would like to make that it gives the value of a max key?

Do i have to rewrite the icomparer?

Answer

fixagon picture fixagon · Jun 1, 2011

Yes you have to rewrite the comparer

example for string as key: (just exchanged x.CompareTo(y) with y.CompareTo(x) )

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

and the call:

SortedList<string, Object> list = new SortedList<string, Object>(new InvertedComparer());