Collection < T > .RemoveAt(Int32)用于删除Collection
句法:
public void RemoveAt (int index);
在这里, index是要删除的元素的从零开始的索引。
异常:如果索引小于零或索引等于或大于Count,则此方法将提供ArgumentOutOfRangeException。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to remove the element
// at the specified index of 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 myColl = new Collection();
// 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 the element at the
// specified index of the Collection
myColl.RemoveAt(2);
// 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);
}
}
}
输出:
Count : 5
A
B
C
D
E
Count : 4
A
B
D
E
范例2:
// C# code to remove the element
// at the specified index of 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 myColl = new Collection();
// 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 the element at the
// specified index of the Collection
// This should raise "ArgumentOutOfRangeException"
// as the index is less than 0
myColl.RemoveAt(-4);
// 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);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
注意:此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.removeat?view=netframework-4.7.2