Using IComparer for sorting

Aadith Ramia picture Aadith Ramia · Jan 15, 2013 · Viewed 100.1k times · Source

I am trying to use an IComparer to sort a list of Points. Here is the IComparer class:

public class CoordinatesBasedComparer : IComparer
{
    public int Compare(Object q, Object r)
    {
        Point a = (p)q;
        Point b = (p)r;
        if ((a.x == b.x) && (a.y == b.y))
            return 0;
        if ((a.x < b.x) || ((a.x == b.x) && (a.y < b.y)))
            return -1;

        return 1;
    }
}

In the client code, I am trying to using this class for sorting a list of points p (of type List<Point>):

CoordinatesBasedComparer c = new CoordinatesBasedComparer();
Points.Sort(c);

The code errors out. Apparently it is expecting IComparer<Point> as argument to sort method.
What do I need to do to fix this?

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Jan 15, 2013

You need to implement the strongly type interface (MSDN).

public class CoordinatesBasedComparer : IComparer<Point>
{
    public int Compare(Point a, Point b)
    {
        if ((a.x == b.x) && (a.y == b.y))
            return 0;
        if ((a.x < b.x) || ((a.x == b.x) && (a.y < b.y)))
            return -1;

        return 1;
    }
}

BTW, I think you use too many braces, I believe they should be used only when they contribute to the compiler. This is my version:

if (a.x == b.x && a.y == b.y)
    return 0;
if (a.x < b.x || (a.x == b.x && a.y < b.y))
    return -1;

Just like I dislike people using return (0).


Note that if you target a .Net-3.5+ application you can use LINQ which is easier and even faster with sorting.

LINQ vesion can be something like:

var orderedList = Points.OrderBy(point => point.x)
                        .ThenBy(point => point.y)
                        .ToList();