Sort A List


	MyListName->Sort();

Sort A List Of Custom Classes

You need to add a CompareTo method to the class which will be used when Sort is called.  It needs to be virtual for C++/CLI and you also need to add :IComparable to the class definition.

Example For An Int Value

(Uses a '.' for the CompareTo call)


	public ref class MyMainClassName : IComparable<MyMainClassName ^>
	{
	public:
		property List<MyClassName^> ^MyClassNames;
		...
	}
	

	public ref class MyListClassName
	{
	public:
		property String ^MyString;
		property int MyInt;

		MyListClassName::MyListClassName(void)
		{
			//Strings and arrays will be nullptr until created
			MyString = "";
		}

		//Add CompareTo to allow sorting of list
		virtual int MyListClassName::CompareTo(MyListClassName ^other)
		{
			return other->MyInt.CompareTo(this->MyInt);		//<<Reverse to reverse sorting order
		}
	};

	MyMainClassName ^MyMainClassName1 = gcnew...
		...
	MyMainClassName->Sort();
Example For A String Value

(Uses '->' for the CompareTo call)


	public ref class MyMainClassName : IComparable<MyMainClassName ^>
	{
	public:
		property List<MyClassName^> ^MyClassNames;
		...
	}
	

	public ref class MyListClassName
	{
	public:
		property String ^MyString;
		property int MyInt;

		MyListClassName::MyListClassName(void)
		{
			//Strings and arrays will be nullptr until created
			MyString = "";
		}

		//Add CompareTo to allow sorting of list
		virtual int MyListClassName::CompareTo(MyListClassName ^other)
		{
			return other->MyString->CompareTo(this->MyString);		//<<Reverse to reverse sorting order
		}
	};

	MyMainClassName ^MyMainClassName1 = gcnew...
		...
	MyMainClassName->Sort();

 

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.