Search code examples
c#sortedlist

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


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?


Solution

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