垂直然后水平排序点 [英] Sort Points vertically then horizontally

查看:57
本文介绍了垂直然后水平排序点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Points数组,我想对它进行垂直和水平排序.

I have an array of Points and i want to sort then both vertically and horizontally.

我应该排序两次吗?

推荐答案

不,您不能仅进行两次排序,因为.Net框架的Sort()算法是一种不稳定的排序,这意味着当您对项目进行排序时,它们的顺序是不考虑原始项的存在,也就是说,当两个项目相等时,它们相对于彼此的位置将是不确定的.

No you can't just sort twice because the .Net framework Sort() algorithm is an unstable sort, which means that when you sort items, the order they originaly were in is not taken into account, that is, when two items are equal, their position relative to each other will be undefined.

您需要做的是为您要排序的类实现一个自定义IComparer,并在对集合进行排序时使用该比较器:

What you will need to do is implement a custom IComparer for the class you are trying to sort and use that comparer when sorting your collection:

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

用法:

List<Point> list = ...;
list.Sort(new PointComparer());

这篇关于垂直然后水平排序点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆