Sort Arrays

	Array::Sort

Will sort an array in numerical order, and you can specify multiple arrays and they will bothbe sorted the same (i.e. an array of peoples names sorted according to another array of their ages), eg:

	Array::Sort(MyArrayWithSortKeys, MyOtherArray);	//Sorts the entire Array using the default comparer.

Sort An Array 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...
		...
	Array::Sort(MyMainClassName);
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...
		...
	Array::Sort(MyMainClassName);

 

 

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.