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

int[] terms;

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

对于那些使用过PHP的人,下面是我试图在c#中做的事情:

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

当前回答

你不能直接这么做。然而,你可以使用Linq来做到这一点:

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

如果数组项在开始时不是空的,您可以先将其转换为List,然后再做您的工作。如:

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

注意:不要错过在文件开头添加'using System.Linq;'。

其他回答

你必须先分配数组:

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;
}

使用Linq的方法,Concat使这变得简单

int[] array = new int[] { 3, 4 };

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

结果 3、4、2

你可以用一个列表。以下是如何

List<string> info = new List<string>();
info.Add("finally worked");

如果你需要返回这个数组

return info.ToArray();

只是不同的方法:

int runs = 0; 
bool batting = true; 
string scorecard;

while (batting = runs < 400)
    scorecard += "!" + runs++;

return scorecard.Split("!");

一种方法是通过LINQ填充数组

如果你想用一个元素填充一个数组 你可以简单地写

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

此外,如果你想用多个元素填充一个数组,你可以使用 循环中的前面代码

//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array

foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}