2010-04-20 96 views

回答

13

而不是使用數組,您可以使用C#中的List<>對象。

List<int> integerList = new List<int>(); 

,反覆列表中包含的項目,使用foreach操作:

foreach(int i in integerList) 
{ 
    // do stuff with i 
} 

您可以添加與Add()Remove()功能列表中的對象的項目。

for(int i = 0; i < 10; i++) 
{ 
    integerList.Add(i); 
} 

integerList.Remove(6); 
integerList.Remove(7); 

可以使用ToArray()功能的List<T>轉換爲數組:

int[] integerArray = integerList.ToArray(); 

這裏是關於List<>對象documentation

+1

我想補充一點,如果你需要一個數組作爲輸出,那麼你可以在完成處理後在列表中調用.ToArray()。 – Paddy 2010-04-20 15:20:33

+0

確保「使用System.Linq」包含在Paddy的想法中。 – 2010-04-20 15:42:35

+0

@Callum:Linq不需要使用ToArray函數。 – 2010-04-20 15:45:26

3

確實聽起來像你應該看看List<T>來代替。

0

數組不是動態的。如果你想動態使用'List<T>'或其他收藏。你總是可以調用ToArray()方法來獲取數組。

1

正如其他人所說,List<T>可能是你想要的。但爲了完整性,您可以使用靜態方法調整數組的大小。例如:

int[] array = { 1, 2, 3 }; 
Array.Resize(ref array, 4);