📌  相关文章
📜  C#|在Collection的指定索引处删除元素<T>

📅  最后修改于: 2021-05-29 19:35:19             🧑  作者: Mango

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);
        }
    }
}

运行时错误:

注意:此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.removeat?view=netframework-4.7.2