Сортировка ArrayList с помощью функции сравнения IComparer C# - PullRequest
0 голосов
/ 12 февраля 2020

Как мне отсортировать список точек, используя настроенный метод сравнения?

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

1 Ответ

2 голосов
/ 12 февраля 2020

Вам лучше использовать интерфейс IComparable<>.

"Сортируемый объект будет реализовывать IComparable, в то время как класс, который будет сортировать объекты, будет реализовывать IComparer."

Источник: разница между IComparable и 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);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...