【问题标题】:Is there a better method of adding an element to an array than iteration? [duplicate]有没有比迭代更好的向数组添加元素的方法? [复制]
【发布时间】: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&lt;T&gt;(或许多其他集合中的任何一个)不是。首先验证你是否想用锤子拧东西。然后看Array.Copy

标签: c# arrays algorithm


【解决方案1】:

您可以使用Array.Resize。但是你真的应该使用ArrayListList&lt;&gt;,它们更容易有效地做到这一点。

【讨论】:

  • 赞成。但不要使用ArrayList,更喜欢通用的List&lt;&gt;
  • 好的,谢谢,我会调查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2016-04-02
  • 2020-06-13
  • 2020-12-06
  • 2010-12-27
相关资源
最近更新 更多