使用 IComparer 进行排序 [英] Using IComparer for sorting

查看:25
本文介绍了使用 IComparer 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 类型):

In the client code, I am trying to using this class for sorting a list of points p (of type List<Point>):

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

代码出错了.显然,它期望 IComparer 作为 sort 方法的参数.
我需要做什么来解决这个问题?

The code errors out. Apparently it is expecting IComparer<Point> as argument to sort method.
What do I need to do to fix this?

推荐答案

您需要实现强类型接口 (MSDN).

You need to implement the strongly type interface (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;
    }
}

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

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;

就像我不喜欢人们使用 return (0) 一样.

Just like I dislike people using return (0).

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

Note that if you target a .Net-3.5+ application you can use LINQ which is easier and even faster with sorting.

LINQ 版本可以是这样的:

LINQ vesion can be something like:

var orderedList = Points.OrderBy(point => point.x)
                        .ThenBy(point => point.y)
                        .ToList();

这篇关于使用 IComparer 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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