cli C++ 对某个属性的对象列表进行排序

Bar*_*t88 2 sorting c++-cli object

我只想对某个属性的列表进行排序。

我有一个LinePiece具有以下属性的对象:

String^ Type;
int X, Y, X2, Y2;
System::String^ Text;
Run Code Online (Sandbox Code Playgroud)

现在我有一个包含这些的列表LinePieces,我想对它们进行排序X value

我发现了一些东西,List->Sort();但我需要提供一些信息。但我不知道如何告诉它根据 X 值对列表进行排序。

那么如何根据对象的 X 值对列表进行排序呢?

Dav*_*Yaw 5

如果我读到你问题的字里行间,听起来有时你想根据X值排序,有时你想根据Y值排序。如果是这种情况,那么我将实现一个Comparer对象,并将其传递给List->Sort()指定它们应如何排序。

public ref class CompareByX : Comparer<LinePiece^>
{
public:
    virtual int Compare(LinePiece^ a,LinePiece^ b) override
    {
        return a->X.CompareTo(b->X);
    }
};

int main(array<System::String ^> ^args)
{
    List<LinePiece^>^ list = ...

    list->Sort(gcnew CompareByX());
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果LinePiece有一个单一的、固有的、通用的排序顺序,那么我会IComparable在类上实现,并使用默认的排序。但是,当您执行此操作时,应小心仅0在两个对象相等时才返回。

当您这样做时,您不需要向 传递任何额外的参数Sort(),因为对象已经知道如何对自身进行排序。

public ref class LinePiece : public IComparable<LinePiece^>
{
public:
    String^ Type;
    int X, Y, X2, Y2;
    String^ Text;

    virtual int CompareTo(LinePiece^ other)
    {
        int result = 0;

        if (result == 0) result = this->X.CompareTo(other->X);
        if (result == 0) result = this->Y.CompareTo(other->Y);
        if (result == 0) result = this->X2.CompareTo(other->X2);
        if (result == 0) result = this->Y2.CompareTo(other->Y2);
        if (result == 0) result = this->Type->CompareTo(other->Type);
        if (result == 0) result = this->Text->CompareTo(other->Text);

        return result;
    }
}

int main(array<System::String ^> ^args)
{
    List<LinePiece^>^ list = ...

    list->Sort();
}
Run Code Online (Sandbox Code Playgroud)