可能是一个非常简单的一个-我开始用c#和需要添加值到一个数组,例如:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
对于那些使用过PHP的人,下面是我试图在c#中做的事情:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
可能是一个非常简单的一个-我开始用c#和需要添加值到一个数组,例如:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
对于那些使用过PHP的人,下面是我试图在c#中做的事情:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
当前回答
如果您不知道数组的大小,或者已经有一个要添加到的现有数组。你可以用两种方式来做这件事。第一个是使用泛型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(…);
这两种方法都允许您动态地进行操作。如果你要添加很多项目,那么只需使用List<T>。如果只有几个项,那么调整数组的大小会有更好的性能。这是因为您在创建List<T>对象时受到了更多的影响。
时间单位为蜱:
3项
数组调整大小时间:6 List添加时间:16
400件
数组大小调整时间:305 List添加时间:20
其他回答
根据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;
}
这允许向数组中添加多个项,或者只是将一个数组作为参数来连接两个数组。
你可以用一个列表。以下是如何
List<string> info = new List<string>();
info.Add("finally worked");
如果你需要返回这个数组
return info.ToArray();
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 * /
使用Linq的方法,Concat使这变得简单
int[] array = new int[] { 3, 4 };
array = array.Concat(new int[] { 2 }).ToArray();
结果 3、4、2
/*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;
}