【问题标题】:Sorting an ArrayList by using IComparer Compare Function C#使用 IComparer 比较函数 C# 对 ArrayList 进行排序
【发布时间】:2020-05-28 11:16:14
【问题描述】:

如何使用自定义比较方法对点列表进行排序?

using System;
using System.Collections;
using System.Collections.Generic;

public class Point : IComparer<Point>
{
    public int x;
    public int y;

    public Point(int x_Point, int y_Point)
    {
        x = x_Point;
        y = y_Point;
    }
    public int Compare(Point a, Point b)
    {
        if (a.x == b.x && a.y == b.y)
            return 0;
        if (a.y < b.y)
            return -1;
        if (a.y == b.y && a.x < b.x)
            return -1;
        return 1;
    }
}

下面的代码在 AL.sort() 处引发错误。

“无法比较数组中的两个元素。” "ArgumentException: 至少一个对象必须实现 IComparable"

我不知道为什么。我在 Points 类中描述自己的比较方法有误吗?

public class ArrayListTest
{
    public static void Main(string[] args)
    {
        ArrayList AL = new ArrayList();
        Random R = new Random();
        for (int i = 0; i < 10; i++)
        {
            Point p = new Point(R.Next(50), R.Next(50));
            AL.Add(p);
        }
        PrintValues(AL);
        AL.Sort();
        PrintValues(AL);
    }
}

【问题讨论】:

  • “一个错误”。我想知道你是否能猜到我的下一个问题......
  • 很抱歉:“无法比较数组中的两个元素。”
  • 不要使用ArrayList,而是使用List&lt;Point&gt;ArrayList 是仿制药出现之前的黑暗时期遗留下来的。此外,您应该实现IComparable 而不是IComparer,因为前者表示该类型可以与相同类型的其他实例进行比较,而后者只是表示它可以比较给定类型的两个实例。
  • 这里有同样的错误:(
  • 这里是你如何设置一个类来比较docs.microsoft.com/en-us/dotnet/api/…

标签: c# compare


【解决方案1】:

您最好使用IComparable&lt;&gt; 接口。

“要排序的对象将实现 IComparable,而要对对象进行排序的类将实现 IComparer。”

来源:difference between IComparable and IComparer

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

    public Point(int x_Point, int y_Point)
    {
        x = x_Point;
        y = y_Point;
    }

    public int CompareTo(Point other)
    {
        if (this.x == other.x && this.y == other.y)
            return 0;
        if (this.y < other.y)
            return -1;
        if (this.y == other.y && this.x < other.x)
            return -1;
        return 1;
    }
}

public static void Main()
{
    var AL = new List<Point>(); // ditch the ArrayList for good... ;-)
    Random R = new Random();
    for (int i = 0; i < 10; i++)
    {
        Point p = new Point(R.Next(50), R.Next(50));
        AL.Add(p);
    }
    PrintValues(AL);
    AL.Sort();
    PrintValues(AL);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2014-04-14
    相关资源
    最近更新 更多