将值添加到C#数组

可能是一个非常简单的一个 – 我开始与C#和需要添加值到一个数组,例如:

int[] terms; for(int runs = 0; runs < 400; runs++) { terms[] = value; } 

对于那些使用过PHP的人来说,下面是我想要在C#中做的事情:

 $arr = array(); for ($i = 0; $i < 10; $i++) { $arr[] = $i; } 

你可以这样做 –

 int[] terms = new int[400]; for (int runs = 0; runs < 400; runs++) { terms[runs] = value; } 

或者,您可以使用列表 – 列表的好处是,在实例化列表时不需要知道数组的大小。

 List<int> termsList = new List<int>(); for (int runs = 0; runs < 400; runs++) { termsList.Add(value); } // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); 

编辑: a)List <T>上的循环比List <T>上的foreach循环便宜2倍以上,b)循环数组比循环List <T>便宜2倍,c)循环使用for的数组比使用foreach (我们大多数人)在List <T>上循环便宜5倍。

如果你用C#3编写,你可以用一行代码来完成:

 int[] terms = Enumerable.Range(0, 400).ToArray(); 

这个代码片段假定你在你的文件的顶部有一个System.Linq的using指令。

另一方面,如果你正在寻找一些可以dynamicresize的东西,因为看起来就是PHP(我从来没有真正学过它),那么你可能想使用List而不是int [] 。 以下代码的样子:

 List<int> terms = Enumerable.Range(0, 400).ToList(); 

但是,请注意,您不能简单地通过将[400]项设置为一个值来添加第401个元素。 你需要调用Add(),像这样:

 terms.Add(1337); 

这里提供了关于如何使用数组的方法。

但是,C#有一个非常方便的东西叫System.Collections 🙂

集合是使用数组的奇妙替代方法,尽pipe其中许多方法在内部使用数组。

例如,C#有一个名为List的集合,其function与PHP数组非常相似。

 using System.Collections.Generic; // Create a List, and it can only contain integers. List<int> list = new List<int>(); for (int i = 0; i < 400; i++) { list.Add(i); } 

您必须先分配数组:

 int [] terms = new int[400]; // allocate an array of 400 ints for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again { terms[runs] = value; } 
 int ArraySize = 400; int[] terms = new int[ArraySize]; for(int runs = 0; runs < ArraySize; runs++) { terms[runs] = runs; } 

那将是我如何编码。

像其他人所描述的那样,使用List作为中介是最简单的方法,但是由于您的input是一个数组,并且您不仅仅希望将数据保存在List中,所以我认为您可能会担心性能。

最有效的方法可能是分配一个新的数组,然后使用Array.Copy或Array.CopyTo。 这并不难,如果你只是想添加一个项目到列表的末尾:

 public static T[] Add<T>(this T[] target, T item) { if (target == null) { //TODO: Return null or throw ArgumentNullException; } T[] result = new T[target.Length + 1]; target.CopyTo(result, 0); result[target.Length] = item; return result; } 

如果需要,我还可以发布插入扩展方法的代码,将目标索引作为input。 这有点复杂,使用静态方法Array.Copy 1-2次。

基于Thracx的回答(我没有足够的回答):

 public static T[] Add<T>(this T[] target, params T[] items) { // Validate the parameters if (target == null) { target = new T[] { }; } if (items== null) { items = new T[] { }; } // Join the arrays T[] result = new T[target.Length + items.Length]; target.CopyTo(result, 0); items.CopyTo(result, target.Length); return result; } 

这允许向数组中添加不止一个项目,或者只是传递一个数组作为参数来连接两个数组。

C#数组是固定长度的并且始终索引。 去Motti的解决scheme:

 int [] terms = new int[400]; for(int runs = 0; runs < 400; runs++) { terms[runs] = value; } 

请注意,这个数组是一个密集数组,一个连续的400个字节的块,你可以放下东西。 如果你想要一个dynamic大小的数组,使用List <int>。

 List<int> terms = new List<int>(); for(int runs = 0; runs < 400; runs ++) { terms.Add(runs); } 

int []和List <int>都不是一个关联数组,它将成为C#中的Dictionary <>。 数组和列表都很密集。

 int[] terms = new int[10]; //create 10 empty index in array terms //fill value = 400 for every index (run) in the array //terms.Length is the total length of the array, it is equal to 10 in this case for (int run = 0; run < terms.Length; run++) { terms[run] = 400; } //print value from each of the index for (int run = 0; run < terms.Length; run++) { Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]); } Console.ReadLine(); 

/ *输出:

索引值为0:400
指数1中的值:400
指数2中的值:400
指数3中的价值:400
指数4:400的价值
价值指数5:400
价值指数6:400
价值指数7:400
指数8:400的价值
价值指数9:400
* /

你不能简单地将一个元素添加到数组中。 您可以将元素设置为给定的位置,但我build议使用List<int>Collection<int>来代替,如果需要将它转换为数组,则使用ToArray()

非常简单的方法

 int[] array =new int[] { 3,4}; array = array.Concat(new int[] { 2 }).ToArray(); 

结果3,4,2

如果你真的需要一个数组,下面几乎是最简单的:

 using System.Collections.Generic; // Create a List, and it can only contain integers. List<int> list = new List<int>(); for (int i = 0; i < 400; i++) { list.Add(i); } int [] terms = list.ToArray(); 
 int[] terms = new int[400]; for(int runs = 0; runs < 400; runs++) { terms[runs] = value; } 
  static void Main(string[] args) { int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/ int i, j; /*initialize elements of array arrayname*/ for (i = 0; i < 5; i++) { arrayname[i] = i + 100; } /*output each array element value*/ for (j = 0; j < 5; j++) { Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]); } Console.ReadKey();/*Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window.*/ } 
  /*arrayname is an array of 5 integer*/ int[] arrayname = new int[5]; int i, j; /*initialize elements of array arrayname*/ for (i = 0; i < 5; i++) { arrayname[i] = i + 100; } 
  int runs = 0; bool batting = true; string scorecard; while (batting = runs < 400) scorecard += "!" + runs++; return scorecard.Split("!"); 

//只是一个不同的方法

如果您不知道数组的大小,或者已经有了要添加的现有数组。 你可以通过两种方式来解决这个问题。 首先是使用通用的List<T> :为此,您需要将数组转换为var termsList = terms.ToList(); 并使用Add方法。 然后当完成使用var terms = termsList.ToArray(); 方法转换回数组。

 var terms = default(int[]); var termsList = terms == null ? new List<int>() : terms.ToList(); for(var i = 0; i < 400; i++) termsList.Add(i); terms = termsList.ToArray(); 

第二种方法是调整当前数组的大小:

 var terms = default(int[]); for(var i = 0; i < 400; i++) { if(terms == null) terms = new int[1]; else Array.Resize<int>(ref terms, terms.Length + 1); terms[terms.Length - 1] = i; } 

如果您使用.NET 3.5 Array.Add(...);

这两个将允许你dynamic地做到这一点。 如果你要添加大量的项目,那么只需使用List<T> 。 如果只是几个项目,那么它将有更好的性能调整数组。 这是因为你创buildList<T>对象需要更多的命中。

时间 蜱:

3个项目

arrays调整时间:6

列表添加时间:16

400个项目

arrays调整时间:305

列表添加时间:20