开发者

how to create a one-dimensional dynamic array in c#?

开发者 https://www.devze.com 2022-12-27 18:31 出处:网络
noob question on c#: how to create a one-dimensional dynamic array? And how to change it later?开发者_如何学运维

noob question on c#: how to create a one-dimensional dynamic array? And how to change it later?

开发者_如何学运维

thanks.


Instead of using an array, you can use the List<> object in C#.

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

To iterate on items contained in the list, use the foreach operator :

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

You can add items in the list object with Add() and Remove() functions.

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

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

You can convert a List<T> to an array using the ToArray() function :

int[] integerArray = integerList.ToArray();

Here is the documentation on List<> object.


Sure sounds like you should look into List<T> instead.


As others have mentioned, a List<T> is likely what you want. But for completeness, you can resize an array using the Array.Resize static method. Example:

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


Arrays are not dynamic. If you want something dynamic use a 'List<T>' or some other collection. You can always call the ToArray() method on it to get an array back.


use either:

ArrayList  //really you should avoid this.
or List<T>

so

var my_list = new List<Your_List_Type_Here>() (Like List<String>);

This way to add you just do:

my_list.Add(Your_Object);

Link to Generic List: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

if you want to go back to an array then just call the ToArray() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号