C# | Remove element at specified index of Collection<T>
Collection<T>.RemoveAt(Int32) is used to remove the element at the specified index of the Collection<T>.
Syntax:
public void RemoveAt (int index);
Here, index is the zero-based index of the element to remove.
Exception: This method will give ArgumentOutOfRangeException if the index is less than zero OR index is equal to or greater than Count.
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.RemoveAt(2);
Console.WriteLine( "Count : " + myColl.Count);
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
}
}
|
Output:
Count : 5
A
B
C
D
E
Count : 4
A
B
D
E
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.RemoveAt(-4);
Console.WriteLine( "Count : " + myColl.Count);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Note: This method is an O(n) operation, where n is Count.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...