[英]How to delete specific element from an array?
如何从数组中删除指定的元素?
例如,我添加了一个数组中的元素,如下所示:
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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.