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

cli C++ sort a objectlist on a certain property

我只是想根据某个 属性 对列表进行排序。

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

String^ Type;
int X, Y, X2, Y2;
System::String^ Text;

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

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

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

如果我从你的问题的字里行间看出,听起来有时你想根据 X 值排序,有时你想根据 Y 值排序。如果是这种情况,那么我将实施一个 Comparer object, and pass that to 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());
}

另一方面,如果 LinePiece 有一个单一的、固有的、通用的排序顺序,那么我会在 class 上实现 IComparable,并使用默认排序。但是,当你这样做的时候,你应该注意只有 return 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();
}