Open In App

C# | List.TrimExcess Method

List<T>.TrimExcess Method is used to set the capacity to the actual number of elements in the List<T>, if that number is less than a threshold value.

Syntax:



public void TrimExcess ();

Note:

Below programs illustrate the use of List<T>.TrimExcess Method:



Example 1:




// C# code to set the capacity to the
// actual number of elements in the List
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a List of strings
        List<string> mylist = new List<string>();
  
        // Inserting elements into List
        mylist.Add("1");
        mylist.Add("2");
        mylist.Add("3");
        mylist.Add("4");
        mylist.Add("5");
  
        // To  display the capacity of list
        Console.WriteLine(mylist.Capacity);
  
        // To display number of elements in List
        Console.WriteLine(mylist.Count);
  
        // using TrimExcess method
        mylist.TrimExcess();
  
        // To  display the capacity of list
        Console.WriteLine(mylist.Capacity);
  
        // To display number of elements in List
        Console.WriteLine(mylist.Count);
    }
}

Output:

8
5
5
5

Example 2:




// C# code to set the capacity to the
// actual number of elements in the List
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a List of integers
        List<int> mylist = new List<int>();
  
        // Inserting elements into List
        mylist.Add(45);
        mylist.Add(78);
        mylist.Add(32);
        mylist.Add(231);
        mylist.Add(123);
        mylist.Add(76);
        mylist.Add(726);
        mylist.Add(716);
        mylist.Add(876);
  
        // To  display the capacity of list
        Console.WriteLine(mylist.Capacity);
  
        // To display number of elements in List
        Console.WriteLine(mylist.Count);
  
        // using TrimExcess method
        mylist.TrimExcess();
  
        // To  display the capacity of list
        Console.WriteLine(mylist.Capacity);
  
        // To display number of elements in List
        Console.WriteLine(mylist.Count);
  
        // using clear method
        mylist.Clear();
  
        // To  display the capacity of list
        Console.WriteLine(mylist.Capacity);
  
        // To display number of elements in List
        Console.WriteLine(mylist.Count);
    }
}

Output:

16
9
9
9
9
0

Reference:


Article Tags :
C#