Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Descending Sorted List

0.00/5 (No votes)
26 May 2008 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here