如何从数组中删除特定元素?

Hol*_*oxx 3 c# arrays

如何从数组中删除指定的元素?

例如,我添加了一个数组中的元素,如下所示:

        int[] array = new int[5];
        for (int i = 0; i < array.Length; i++) 
        {
            array[i] = i;
        }
Run Code Online (Sandbox Code Playgroud)

如何从索引2中删除元素?

Cha*_*ion 10

使用内置System.Collections.Generic.List<T>类.如果你想删除元素,不要让你的生活比以前更难.

list.RemoveAt(2);
Run Code Online (Sandbox Code Playgroud)

请记住,执行此操作的实际代码并不复杂.问题是,为什么不利用内置类?

public void RemoveAt(int index)
{
    if (index >= this._size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException();
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this._items, index + 1, this._items, index, this._size - index);
    }
    this._items[this._size] = default(T);
    this._version++;
}
Run Code Online (Sandbox Code Playgroud)