使用 IComparer 进行排序

2023-12-12

我正在尝试使用IComparer对点列表进行排序。这是 IComparer 类:

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

在客户端代码中,我尝试使用此类对点 p 列表(类型为List<Point>):

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

代码出错了。显然是在期待IComparer<Point>作为排序方法的参数。
我需要做什么来解决这个问题?


您需要实现强类型接口(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;
    }
}

顺便说一句,我认为你使用了太多大括号,我相信只有当它们对编译器有贡献时才应该使用它们。这是我的版本:

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 (0).


请注意,如果您的目标是 .Net-3.5+ 应用程序,则可以使用 LINQ,它的排序更容易、更快。

LINQ 版本可以是这样的:

var orderedList = Points.OrderBy(point => point.x)
                        .ThenBy(point => point.y)
                        .ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 IComparer 进行排序 的相关文章

随机推荐