C# Queue.TrimExcess() Method with Examples


The Queue.TrimExcess() method in C# is used to set the capacity to the actual number of elements in the Queue<T>, if that number is less than 90 percent of current capacity.

Syntax

public void TrimExcess ();

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);
      Console.WriteLine("Queue...");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Count of elements in the Queue = "+queue.Count);
      queue.Clear();
      queue.TrimExcess();
      Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count);
   }
}

Output

100
200
300
400
500
600
700
800
900
1000
Count of elements in the Queue = 10
Count of elements in the Queue [Updated] = 0

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Does the queue has element Jack? = "+queue.Contains("Jack"));
      queue.TrimExcess();
      queue.Clear();
      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

Output

Count of elements = 8
Does the queue has element Jack? = True
Count of elements (updated) = 0

Updated on: 02-Dec-2019

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements