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

 

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.