C#中的动态数组


111

有什么方法可以在C#中创建动态数组?


1
如果仍然卡在旧的泥浆中,则可以使用[]代替List <>,则可以使用Array.Resize()。这是一个很好的例子。dotnetperls.com/array-resize
Gian

链接dotnetperls.com/array-resize不起作用。(FYI)
Su Llewellyn

Answers:


149

看一眼 通用列表


13
问题(尽管简短且不具描述性)不是在询问通用列表-问题可能是在询问dynamic[] msdn.microsoft.com/zh-CN/library/dd264736.aspx(动态类型数组)或ExpandoObject msdn.microsoft.com/ zh-cn / library /…我可以-1不用提及这些的答案
Luke T O'Brien

5
@ LukeTO'Brien,C#4.0中引入了动力学,该函数在最初提出此问题后整整发布了一年。OP可能正在询问可调整大小的数据结构,例如en.wikipedia.org/wiki/Dynamic_array
Brian Merrell,

6
仅包含文章链接的答案无济于事。无法保证链接将保持活动状态。
JamEngulfer

@JamEngulfer这是不正确的。如果他的链接文本是“看看此”并链接了“此”,那么我会同意你的看法。如果您删除链接,然后看一下还剩下什么,OP的“看一看通用列表”的答案就是很多信息,可以让任何将来的读者都在搜寻…………
Lynn Crumbling

88

用代码示例扩展Chris和Migol的答案。

使用数组

Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");

使用通用列表。List <T>类在后台使用数组进行存储,但是这样做的方式使其可以有效地增长。

List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];

2
这个例子很糟糕,因为我们都讨论了ArrayList
Migol,2009年

21
这个答案比您的@Migol更好,因为这说明了如何实际使用List <>而不是仅仅将其提及为关键字。“半坏”->“半好”->好
fhugas

56

有时,普通数组比通用列表更可取,因为它们更方便(例如,对于昂贵的计算,性能更好-例如数字代数应用,或与R或Matlab等统计软件交换数据)

在这种情况下,您可以在动态启动列表之后使用ToArray()方法。

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

当然,只有在数组大小未知或事前不固定的情况下,这才有意义。如果您已经在程序的某个点知道了数组的大小,则最好将其作为固定长度的数组启动。(例如,如果您从ResultSet检索数据,则可以计算其大小并动态启动该大小的数组)


1
只要使用索引器,就不值得。
aaimnr 2011年

2
Araries并不方便(它们提供List <T>接口的子集)并且提供几乎相同的性能,因为List <T>在其下方使用常规数组。迭代6000000个元素:列表/为:1971ms阵列/为:1864ms(基准从stackoverflow.com/questions/454916/...
aaimnr

9
如果必须将数组传递给接口,则它必须是数组。建立列表然后将其传递到数组中之前,要容易得多。我比其他人更喜欢这个答案,因为它解决了这个问题!
Michael Stimson 2014年

36

List<T>适用于强类型代码,或者ArrayList您具有.NET 1.1或喜欢转换变量。


2

动态数组示例:

Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];

for (int i = 0; i < number; i++)
{
    arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
    Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();

2

您可以使用动态对象执行此操作:

var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };

foreach(var keyvalue in dynamicKeyValueArray)
{
    Console.Log(keyvalue.Key);
    Console.Log(keyvalue.Value);
}

1

使用实际上是实现数组的数组列表。它最初需要大小为4的数组,并在数组满时会创建一个具有两倍大小的新数组,并将第一个数组的数据复制到第二个数组中,现在将新项插入到新数组中。同样,第二个数组的名称会创建第一个数组的别名,以便可以使用与前一个相同的名称进行访问,并且第一个数组会被处理



0

您可以使用collections类中的arraylist对象

using system.collections;
   static void main()
        {
        Arrylist arr=new Arrylist();
         }

您想添加可使用的元素吗

arr.add();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.