SortedList::TrimToSize Method ()
Sets the capacity to the actual number of elements in a SortedList object.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| NotSupportedException |
This method can be used to minimize a collection's memory overhead if no new elements will be added to the collection.
To reset a SortedList object to its initial state, call the Clear method before calling TrimToSize. Trimming an empty SortedList sets the capacity of the SortedList to the default capacity.
This method is an O(n) operation, where n is Count.
The following code example shows how to trim the unused portions of a SortedList object and how to clear its values.
#using <system.dll> using namespace System; using namespace System::Collections; void PrintKeysAndValues( SortedList^ myList ) { Console::WriteLine( "\t-KEY-\t-VALUE-" ); for ( int i = 0; i < myList->Count; i++ ) { Console::WriteLine( "\t{0}:\t{1}", myList->GetKey( i ), myList->GetByIndex( i ) ); } Console::WriteLine(); } int main() { // Creates and initializes a new SortedList. SortedList^ mySL = gcnew SortedList; mySL->Add( "one", "The" ); mySL->Add( "two", "quick" ); mySL->Add( "three", "brown" ); mySL->Add( "four", "fox" ); mySL->Add( "five", "jumped" ); // Displays the count, capacity and values of the SortedList. Console::WriteLine( "Initially," ); Console::WriteLine( " Count : {0}", mySL->Count ); Console::WriteLine( " Capacity : {0}", mySL->Capacity ); Console::WriteLine( " Values:" ); PrintKeysAndValues( mySL ); // Trims the SortedList. mySL->TrimToSize(); // Displays the count, capacity and values of the SortedList. Console::WriteLine( "After TrimToSize," ); Console::WriteLine( " Count : {0}", mySL->Count ); Console::WriteLine( " Capacity : {0}", mySL->Capacity ); Console::WriteLine( " Values:" ); PrintKeysAndValues( mySL ); // Clears the SortedList. mySL->Clear(); // Displays the count, capacity and values of the SortedList. Console::WriteLine( "After Clear," ); Console::WriteLine( " Count : {0}", mySL->Count ); Console::WriteLine( " Capacity : {0}", mySL->Capacity ); Console::WriteLine( " Values:" ); PrintKeysAndValues( mySL ); // Trims the SortedList again. mySL->TrimToSize(); // Displays the count, capacity and values of the SortedList. Console::WriteLine( "After the second TrimToSize," ); Console::WriteLine( " Count : {0}", mySL->Count ); Console::WriteLine( " Capacity : {0}", mySL->Capacity ); Console::WriteLine( " Values:" ); PrintKeysAndValues( mySL ); } /* This code produces the following output. Initially, Count : 5 Capacity : 16 Values: -KEY- -VALUE- five: jumped four: fox one: The three: brown two: quick After TrimToSize, Count : 5 Capacity : 5 Values: -KEY- -VALUE- five: jumped four: fox one: The three: brown two: quick After Clear, Count : 0 Capacity : 16 Values: -KEY- -VALUE- After the second TrimToSize, Count : 0 Capacity : 16 Values: -KEY- -VALUE- */
Available since 10
.NET Framework
Available since 1.1