可能是一个非常简单的一个-我开始用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#和需要添加值到一个数组,例如:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
对于那些使用过PHP的人,下面是我试图在c#中做的事情:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
当前回答
根据Thracx的回答(我没有足够的分数来回答):
public static T[] Add<T>(this T[] target, params T[] items)
{
// Validate the parameters
if (target == null) {
target = new T[] { };
}
if (items== null) {
items = new T[] { };
}
// Join the arrays
T[] result = new T[target.Length + items.Length];
target.CopyTo(result, 0);
items.CopyTo(result, target.Length);
return result;
}
这允许向数组中添加多个项,或者只是将一个数组作为参数来连接两个数组。
其他回答
如果你真的需要一个数组,下面可能是最简单的:
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
int [] terms = list.ToArray();
你必须先分配数组:
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;
}
你不能直接这么做。然而,你可以使用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;'。
c#数组是固定长度的,并且总是有索引。遵循Motti的解决方案:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
请注意,这个数组是一个密集数组,一个400字节的连续块,您可以在其中删除内容。如果你想要一个动态大小的数组,使用List<int>。
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
int[]和List<int>都不是关联数组——这在c#中是Dictionary<>。数组和列表都是密集的。
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}