向C#数组添加值

19 浏览
0 Comments

向C#数组添加值

这可能是一个非常简单的问题 - 我正在学习C#,需要向数组中添加值,例如:

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

对于那些使用过PHP的人来说,这就是我想在C#中做的事情:

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

admin 更改状态以发布 2023年5月22日
0
0 Comments

使用 Linq Concat 方法使这个过程变得简单

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

结果是3,4,2

0
0 Comments

你可以这样做 -

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

或者,你可以使用列表 - 列表的优势在于,当实例化列表时,不需要知道数组大小。

List termsList = new List();
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上的for循环,比List上的foreach循环便宜多了,b) 在数组上循环比在List上循环便宜约两倍,c) 使用for在数组上循环比使用foreach在List上循环便宜五倍(我们中的大多数人都这样做)。

0