如何从数组中删除指定元素?
例如,我像这样从一个数组中添加了元素:
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
如何删除索引为2的元素?System.Collections.Generic.List<T>
类。如果要删除元素,不要让生活变得更加困难。list.RemoveAt(2);
请记住实现这个并不那么复杂。关键是,为什么不利用内置类呢?
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++;
}