4

我想先根据 x 再根据 y 对 C# 中的类点列表(见下文)进行排序。

public class Point
{
    public int x;
    public int y;
    public Point(int xp, int yp)
    {
        x = xp;
        y = yp;
    }
}

你是怎么做到的:我是 C# 的新手,并且与 Java 比较方法有什么相似之处,这些方法实现了类的自定义比较器,而且我想将比较方法(int CompareTo)添加到类中以排序班级。

提前致谢。

4

4 回答 4

8

是的,您正在寻找IComparable<T>and IComparer<T>- 后者相当于Comparator<E>Java 中的接口。

如果您想添加与Point类本身的比较,请Point实现IComparable<Point>(也可能是非泛型IComparable接口)。如果您想在其他地方实现比较,请让另一个类实现IComparer<Point>

对于等式,.NET 也有IEquatable<T>IEqualityComparer<T>。这些用于诸如Dictionary<,>.

作为旁注,我强烈建议您不要使用公共字段 - 您可能很想制作 variables readonly。(不可变类型通常更容易推理。)您可能决定制作Pointa structtoo,而不是 a class

于 2012-09-13T05:17:00.647 回答
4
var points = new List<Point>() { new Point(1,3), new Point(1,4), new Point(1,2) };
var sortedPoints = points.OrderBy(point => point.x).ThenBy(point => point.y);
于 2012-09-13T05:17:04.467 回答
1

您可以实现IComparable接口并实现其

public int CompareTo( object obj )

在这个方法中,您可以编写逻辑来比较两个对象,例如:

if (objectA.x > objectB.x)
  return 1
else if (objectA.x < objectB.x)
  return -1
else // compare y in both objects
于 2012-09-13T05:18:42.260 回答
0

您要在 C# 中实现的接口是IComparable<T>,它的作用类似于 Java 的 Comparable。然后你的代码变成

public class Point : IComparable<Point>
{
    private int x;
    private int y;

    public int X
    {
        get { return x; }
    }

    public int Y
    {
        get { return y; }
    }

    public Point(int xp, int yp)
    {
        x = xp;
        y = yp;
    }

    public int CompareTo(Point other)
    {
        // Custom comparison here
    }
}

请注意,我将公共字段更改为私有字段,并将面向公众的接口更改为properties。这是更惯用的 C# - 公共字段在 Java 和 C# 中都不受欢迎。

于 2012-09-13T05:17:59.613 回答