Open In App

C# | Remove all elements from the Collection<T>

Improve
Improve
Like Article
Like
Save
Share
Report

Collection<T>.Clear method is used to remove all elements from the Collection<T>.

Syntax:

public void Clear ();

Below given are some examples to understand the implementation in a better way:

Example 1:




// C# code to remove all
// elements from the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection<string> myColl = new Collection<string>();
  
        // Adding elements in Collection myColl
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(string str in myColl)
        {
            Console.WriteLine(str);
        }
  
        // Removing all the elements from Collection
        myColl.Clear();
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(string str in myColl)
        {
            Console.WriteLine(str);
        }
    }
}


Output:

Count : 5
A
B
C
D
E
Count : 0

Example 2:




// C# code to remove all
// elements from the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of ints
        Collection<int> myColl = new Collection<int>();
  
        // Adding elements in Collection myColl
        myColl.Add(2);
        myColl.Add(3);
        myColl.Add(4);
        myColl.Add(5);
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(int i in myColl)
        {
            Console.WriteLine(i);
        }
  
        // Removing all the elements from Collection
        myColl.Clear();
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(int i in myColl)
        {
            Console.WriteLine(i);
        }
    }
}


Output:

Count : 4
2
3
4
5
Count : 0

Note:

  • Count is set to zero, and references to other objects from elements of the collection are also released.
  • This method is an O(n) operation, where n is Count.

Reference:



Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads