C# | Remove all elements from the Collection<T>
Last Updated :
01 Feb, 2019
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:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< string > myColl = new Collection< string >();
myColl.Add( "A" );
myColl.Add( "B" );
myColl.Add( "C" );
myColl.Add( "D" );
myColl.Add( "E" );
Console.WriteLine( "Count : " + myColl.Count);
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
myColl.Clear();
Console.WriteLine( "Count : " + myColl.Count);
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
}
}
|
Output:
Count : 5
A
B
C
D
E
Count : 0
Example 2:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< int > myColl = new Collection< int >();
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
Console.WriteLine( "Count : " + myColl.Count);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
myColl.Clear();
Console.WriteLine( "Count : " + myColl.Count);
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:
Share your thoughts in the comments
Please Login to comment...