Using IComparer for sorting

前端 未结 4 678
南方客
南方客 2020-11-28 10:31

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

public class CoordinatesBasedComparer : IComparer
{
    p         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 10:48

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

    public class CoordinatesBasedComparer : IComparer
    {
        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();
    

提交回复
热议问题