【发布时间】:2015-01-01 20:15:35
【问题描述】:
每当我需要向数组中添加元素时,我总是使用这种算法
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;
但是我想知道是否有更好的方法来做到这一点,因为对于更大的数组,这将需要大量的计算时间。
【问题讨论】:
-
数组是固定大小的,
List<T>(或许多其他集合中的任何一个)不是。首先验证你是否想用锤子拧东西。然后看Array.Copy。