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

发布于 2024-08-31 23:32:01 字数 472 浏览 5 评论 0原文

我试图首先按 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

I am trying to sort a List of 2D Points first by x co-ordinate and then by y co-ordinate.
I implemented the IComparer interface as follows:

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;
        }

    }
}

And then call my sorting as follows:

pointsList.Sort(new PointComparer());

For some reason the list doesn't sort. Surely is something very simple and silly, but stuck on this for quite a while....TIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浊酒尽余欢 2024-09-07 23:32:01

这应该效果更好:

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)

This should work better:

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;
    }

  }
}

If the X values are different, it will use the Y value for sorting. This is different from your code, where X values will be used if the Y values are the same.

As others have mentioned, if you can use Linq, you should use the OrderBy and ThenBy extension methods:

pointsList.OrderBy(p => p.X).ThenBy(p => p.y)
や三分注定 2024-09-07 23:32:01

为什么不:

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

Why not:

var sorted = pointsList.OrderBy(p => p.X)
                       .ThenBy(p => p.y)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文