有没有比迭代更好的将元素添加到数组的方法
本文关键字:添加 数组 方法 元素 迭代 更好 有没有 | 更新日期: 2023-09-27 18:35:47
每当我需要将元素添加到数组中时,我总是使用这个算法
data toAdd = 10;
data[] theArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
data[] tempArray = new int[theArray.Length + 1];
for (int i = 0; i < theArray.Length; i++)
{
tempArray[i] = theArray[i];
}
theArray = new data[tempArray.Length];
for (int i = 0; i < theArray.Length; i++)
{
theArray[i] = tempArray[i];
}
theArray[theArray.Length - 1] = toAdd;
但是,我想知道是否有更好的方法来做到这一点,因为对于更大的数组,这将需要大量的计算时间。
您可以使用
Array.Resize
.但是您确实应该使用更轻松有效地执行此操作的ArrayList
或List<>
。