Home  |  Delphi .net Home  |  System.Collections.SortedList  |  TrimToSize Method
  
TrimToSize  
Method  
Removes unused elements from the current SortedList
SortedList Class
System.Collections NameSpace
CF1.  Procedure TrimToSize ;
CF : Methods with this mark are Compact Framework Compatible
Description
The TrimToSize method removes unused capacity from the current SortedList. The new Capacity is therefore set equal to the Count of elements.
 
However, if the list has a Zero count, then the capacity is set to the default size of 16.
Microsoft MSDN Links
System.Collections
System.Collections.SortedList
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

 Buy Proxies at
 Buyproxies.io
 
 
 
Illustrating the effects of TrimToSize and Clear
program Project1;
{$APPTYPE CONSOLE}

uses
  System.Collections;

var
  List      : System.Collections.SortedList;
  i         : Integer;

begin
  // Create our sorted list object with a capacity if 10 elements
  List := SortedList.Create(10);

  // Fill it
  List['0.'] := 'Zero';
  List['1.'] := 'One';
  List['2.'] := 'Two';
  List['3.'] := 'Three';

  Console.WriteLine('List Count    = {0}', List.Count.ToString);
  Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
  Console.WriteLine;

  // Display List contents : note the 0 indexing
  for i := 0 to List.Count-1 do
    Console.WriteLine('{0} = {1}',
                      List.GetKey(i).ToString,
                      List.GetByIndex(i).ToString);

  // Trim the list to remove unused elements
  List.TrimToSize;

  Console.WriteLine;
  Console.WriteLine('After 1st TrimToSize :');
  Console.WriteLine;
  Console.WriteLine('List Count    = {0}', List.Count.ToString);
  Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
  Console.WriteLine;

  // Clear the list
  List.Clear;

  Console.WriteLine;
  Console.WriteLine('After Clear :');
  Console.WriteLine;
  Console.WriteLine('List Count    = {0}', List.Count.ToString);
  Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);

  // Trim the list again
  List.TrimToSize;

  Console.WriteLine;
  Console.WriteLine('After 2nd TrimToSize :');
  Console.WriteLine;
  Console.WriteLine('List Count    = {0}', List.Count.ToString);
  Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
  Console.WriteLine;

  Console.Readline;
end.
   List Count    = 4
   List Capacity = 10
  
   List[0] = 0.
   List[1] = 1.
   List[2] = 2.
   List[3] = 3.
  
   After 1st TrimToSize :
  
   List Count    = 4
   List Capacity = 4
  
  
   After Clear :
  
   List Count    = 0
   List Capacity = 16   // This is incorrect at the time of writing
  
   After 2nd TrimToSize :
  
   List Count    = 0
   List Capacity = 16
 
 
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Contact the author