提升价值,以一个C#数组 [英] Adding values to a C# array

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

问题描述

大概是一个非常简单的这一点 - 我开始接触C#和需要值添加到一个数组,例如:

  INT []条件;对于(INT运行= 0;&运行LT; 400;运行++)
{
    术语[] =价值;
}

对于那些谁使用PHP,这里就是我想在C#中要做到:

  $ ARR =阵列();
为($ I = 0; $ I小于10; $ I ++){
    $常用3 [] = $ I;
}


解决方案

您可以做到这一点的方式 -

  INT [] =方面新INT [400];
对于(INT运行= 0;&运行LT; 400;运行++)
{
    术语[运行] =价值;
}

另外,您也可以使用列表 - 优势与名单之中,实例化列表时,你并不需要知道数组大小

 列表< INT> termsList =新的List< INT>();
对于(INT运行= 0;&运行LT; 400;运行++)
{
    termsList.Add(值);
}//你可以把它转换回一个数组,如果你想
INT [] =术语termsList.ToArray();

编辑: 一)在循环列表与LT; T>是一个位超过2倍,比便宜的的foreach 环路上表< T>,b)关于阵列循环大约比循环的名单,LT便宜2倍; T>,C)上使用阵列循环作为比循环的名单,LT便宜5倍;使用T> 的foreach (其中我们大多数人)

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[] = value;
}

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

解决方案

You can do this way -

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();

Edit: 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天全站免登陆