将值添加到 C# 数组 [英] Adding values to a C# array

查看:35
本文介绍了将值添加到 C# 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的 - 我从 C# 开始,需要向数组添加值,例如:

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:

int[] terms;

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

对于那些使用过 PHP 的人,这是我在 C# 中尝试做的事情:

For those who have used PHP, here's what I'm trying to do in C#:

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

推荐答案

你可以这样做 -

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

或者,您可以使用列表 - 列表的优点是,在实例化列表时您不需要知道数组大小.

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

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 上的 for 循环是比 List 上的 foreach 循环便宜 2 倍多,b) 在数组上循环比在 List 上循环便宜大约 2 倍,c) 使用 for 在数组上循环 比使用 foreach(我们大多数人都这样做)在 List 上循环便宜 5 倍.

a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).

这篇关于将值添加到 C# 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆