可能是一个非常简单的一个-我开始用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# 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);

其他回答

你不能直接这么做。然而,你可以使用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;'。

数组推送示例

public void ArrayPush<T>(ref T[] table, object value)
{
    Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
    table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
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 * /

下面是如何处理向数组中添加新数字和字符串的一种方法:

int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];

do
{
    for (int i = 0; i < names.Length; i++)
    {
        Console.WriteLine("Enter Name");
        names[i] = Convert.ToString(Console.ReadLine());
        Console.WriteLine($"The Name is: {names[i]}");
        Console.WriteLine($"the index of name is: {i}");
        Console.WriteLine("Enter ID");
        ids[i] = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine($"The number is: {ids[i]}");
        Console.WriteLine($"the index is: {i}");
    }


} while (names.Length <= 10);

一种方法是通过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();
}