可能是一个非常简单的一个-我开始用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;
}
当前回答
这里提供了关于如何使用数组来做到这一点的答案。
然而,c#有一个非常方便的东西叫做System。集合
集合是使用数组的理想替代品,尽管其中许多在内部使用数组。
例如,c#有一个名为List的集合,其功能与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);
}
其他回答
如果你真的需要一个数组,下面可能是最简单的:
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 ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
这就是我的编码方式。
如果你用c# 3编写代码,你可以用一行代码来实现:
int[] terms = Enumerable.Range(0, 400).ToArray();
这段代码片段假设您有一个System的using指令。Linq在你的文件顶部。
另一方面,如果您正在寻找可以动态调整大小的东西,这似乎是PHP的情况(我实际上从未学习过它),那么您可能希望使用List而不是int[]。下面是代码的样子:
List<int> terms = Enumerable.Range(0, 400).ToList();
但是请注意,不能通过设置terms[400]来简单地添加第401个元素。相反,你需要像这样调用Add():
terms.Add(1337);
你可以这样做
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;
}