可能是一个非常简单的一个-我开始用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#将列表值添加到字符串数组中,而不使用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

其他回答

你必须先分配数组:

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

这对我来说似乎不那么麻烦:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.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 * /

如果您不知道数组的大小,或者已经有一个要添加到的现有数组。你可以用两种方式来做这件事。第一个是使用泛型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

到2019年,你可以使用LinQ在一行中使用Append, Prepend

using System.Linq;

然后在NET 6.0中:

terms = terms.Append(21);

或低于NET 6.0的版本

terms = terms.Append(21).ToArray();