gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:41:41 25 4
gpt4 key购买 nike

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

例如我从这样的数组中添加元素:

        int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}

如何删除索引2的元素?

最佳答案

使用内置的 System.Collections.Generic.List<T>类(class)。如果你想删除元素,不要让你的生活变得比它必须的更难。

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

关于c# - 如何从数组中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4777719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com