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

查看:68
本文介绍了使用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<Point>)的列表进行排序:

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<Point>作为排序方法的参数.
我该怎么做才能解决此问题?

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

推荐答案

您需要实现强类型接口(

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 vesion可能类似于:

LINQ vesion can be something like:

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

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

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