对2D点列表进行排序(首先是X然后是Y)

时间:2010-05-08 15:04:39

标签: c# sorting icomparable points

我试图先按x坐标然后按y坐标对2D点列表进行排序。 我按如下方式实现了IComparer接口:

class PointComparer : IComparer<Point>
{
    public int Compare(Point x, Point y)
    {
        if (x.Y != y.Y)
        {
            return x.Y - y.Y;
        }
        else
        {
            return x.X - y.X;
        }

    }
}

然后按如下方式调用我的排序:

pointsList.Sort(new PointComparer());

由于某种原因,列表不排序。肯定是非常简单和愚蠢的事情,但坚持了很长一段时间...... TIA

3 个答案:

答案 0 :(得分:6)

这应该更好:

class PointComparer : IComparer<Point>
{
  public int Compare(Point first, Point second)
  {
    if (first.X == second.X)
    {
        return first.Y - second.Y;
    }
    else
    {
        return first.X - second.X;
    }

  }
}

如果X值不同,它将使用Y值进行排序。这与您的代码不同,如果Y值相同,将使用X值。

正如其他人所提到的,如果你可以使用Linq,你应该使用OrderByThenBy扩展方法:

pointsList.OrderBy(p => p.X).ThenBy(p => p.y)

答案 1 :(得分:1)

你能不能使用OrderBy - &gt; ThenBy?

http://msdn.microsoft.com/en-us/library/bb534743.aspx

答案 2 :(得分:0)

为什么不:

var sorted = pointsList.OrderBy(p => p.X)
                       .ThenBy(p => p.y)
相关问题