65.9K
CodeProject is changing. Read more.
Home

Descending Sorted List

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.75/5 (3 votes)

May 27, 2008

CPOL
viewsIcon

42662

What if you want the object to be sorted in descending order?

Introduction

Microsoft gives us an out-of-the-box sorted list object which sorts its items automatically.

But what if you want the object to be sorted in descending order?

Using the Code

Create the following class:

internal class DescendingComparer : IComparer
    { 
        public int Compare(object x, object y)
        {
            try
            {
                return System.Convert.ToInt32(x).CompareTo
                    (System.Convert.ToInt32(y)) * -1;
            }
            catch (Exception ex)
            {
                return x.ToString().CompareTo(y.ToString());
            }
        } 
    }

And then create the sorted list:

Sorted List clsScoresDesc = new SortedList(new DescendingComparer());

But... it was still not good enough for me because my key was double, so I created the following class:

internal class DoubleComparer : IComparer<double>
    {
        const double eps = 1E-10;
        public int Compare(double x, double y)
        { return y > x + eps ? 1 : y < x - eps ? -1 : 0; }
    } 

And then the sorted list:

IComparer<double> doubleComparer = new DoubleComparer ();
slAdComponent = new SortedList<double, myComponent>( doubleComparer);

You can also iterate through the sorted list using the for loop upside down, but I like the IComparer.

History

  • 27th May, 2008: Initial post