可能是一个非常简单的一个-我开始用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;
}
或者,你也可以使用列表——列表的优点是,当实例化列表时,你不需要知道数组的大小。
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倍(我们大多数人都这样做)。
其他回答
你必须先分配数组:
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[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
只是不同的方法:
int runs = 0;
bool batting = true;
string scorecard;
while (batting = runs < 400)
scorecard += "!" + runs++;
return scorecard.Split("!");
c#数组是固定长度的,并且总是有索引。遵循Motti的解决方案:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
请注意,这个数组是一个密集数组,一个400字节的连续块,您可以在其中删除内容。如果你想要一个动态大小的数组,使用List<int>。
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
int[]和List<int>都不是关联数组——这在c#中是Dictionary<>。数组和列表都是密集的。
使用c#将列表值添加到字符串数组中,而不使用ToArray()方法
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
string[] values = new string[list.Count];//assigning the count for array
for(int i=0;i<list.Count;i++)
{
values[i] = list[i].ToString();
}
值数组的输出包含:
one
two
三个
four
five