可能是一个非常简单的一个-我开始用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;
}
当前回答
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
其他回答
你可以这样做
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>上的for循环比List<T>上的foreach循环便宜2倍多,b)在数组上的循环比在List<T>上的循环便宜2倍左右,c)使用for在数组上的循环比使用foreach在List<T>上的循环便宜5倍(我们大多数人都这样做)。
如果您不知道数组的大小,或者已经有一个要添加到的现有数组。你可以用两种方式来做这件事。第一个是使用泛型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
这对我来说似乎不那么麻烦:
var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
你不能简单地向数组中添加一个元素。您可以将元素设置在给定位置,如fallen888所述,但我建议使用List<int>或Collection<int>,如果需要将其转换为数组,则使用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 * /