可能是一个非常简单的一个-我开始用c#和需要添加值到一个数组,例如:

int[] terms;

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

对于那些使用过PHP的人,下面是我试图在c#中做的事情:

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

当前回答

正如其他人所描述的那样,使用List作为中介是最简单的方法,但由于您的输入是一个数组,并且您不希望将数据保存在List中,因此我假定您可能关心性能。

最有效的方法可能是分配一个新数组,然后使用array。Copy或Array.CopyTo。如果你只是想在列表的末尾添加一个项目,这并不难:

public static T[] Add<T>(this T[] target, T item)
{
    if (target == null)
    {
        //TODO: Return null or throw ArgumentNullException;
    }
    T[] result = new T[target.Length + 1];
    target.CopyTo(result, 0);
    result[target.Length] = item;
    return result;
}

如果需要,我还可以发布以目标索引作为输入的Insert扩展方法的代码。它稍微复杂一点,使用静态方法Array。复制1-2次。

其他回答

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

这允许向数组中添加多个项,或者只是将一个数组作为参数来连接两个数组。

int ArraySize = 400;

int[] terms = new int[ArraySize];


for(int runs = 0; runs < ArraySize; runs++)
{

    terms[runs] = runs;

}

这就是我的编码方式。

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

using System.Linq;

然后在NET 6.0中:

terms = terms.Append(21);

或低于NET 6.0的版本

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

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

一种方法是通过LINQ填充数组

如果你想用一个元素填充一个数组 你可以简单地写

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

此外,如果你想用多个元素填充一个数组,你可以使用 循环中的前面代码

//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array

foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}