将值添加到C#数组

Ros*_*oss 473 c# arrays

可能是一个非常简单的 - 我开始使用C#并且需要为数组添加值,例如:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}
Run Code Online (Sandbox Code Playgroud)

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

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}
Run Code Online (Sandbox Code Playgroud)

Tam*_*ege 779

你可以这样做 -

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

编辑: a)List <T>上的for循环比List <T>上的foreach循环便宜2倍以上,b)数组上的循环比List <T>上的循环便宜2倍左右,c)循环上使用for的数组比使用foreach(我们大多数人都这样做)在List <T>上循环便宜5倍.

  • @PhillHealey在创建数组之前,您不必"知道"数组有多大.正如您所看到的,在这些示例中,OP必须将值放入"new int [400]" - 但是对于列表,他不必这样做. (7认同)
  • @ T.Todua如果您像建议的那样创建一个空数组,然后尝试访问它不存在的索引来设置值,那么一旦运行代码就会得到一个`OutOfRangeException`.数组需要使用你要使用的大小进行初始化,它们在开始时保留所有空间,使得它们非常快,但不可能调整大小. (5认同)
  • 第一位代码不会是任何东西,因为值没有在任何地方定义.-_- (3认同)
  • 在这种情况下使用列表有什么好处? (2认同)

Dav*_*ell 84

如果你用C#3写作,你可以使用单行代码:

int[] terms = Enumerable.Range(0, 400).ToArray();
Run Code Online (Sandbox Code Playgroud)

此代码段假定您在文件顶部有System.Linq的using指令.

另一方面,如果你正在寻找可以动态调整大小的东西,因为它似乎是PHP的情况(我从来没有真正学过它),那么你可能想要使用List而不是int [] .这代码的样子:

List<int> terms = Enumerable.Range(0, 400).ToList();
Run Code Online (Sandbox Code Playgroud)

但请注意,您不能通过将术语[400]设置为值来简单地添加第401个元素.你需要调用Add(),如下所示:

terms.Add(1337);
Run Code Online (Sandbox Code Playgroud)


Yit*_*erg 57

使用Linq的方法Concat使这很简单

int[] array = new int[] { 3, 4 };

array = array.Concat(new int[] { 2 }).ToArray();
Run Code Online (Sandbox Code Playgroud)

结果3,4,2

  • 该方法将向数组中添加400个项目,以多出一个空间来创建该数组的副本,并将所有元素移至新数组400次。因此不建议您明智地使用性能。 (11认同)

Fly*_*wat 37

这里提供了有关如何使用数组进行操作的答案.

但是,C#有一个非常方便的东西,叫做System.Collections :)

集合是使用数组的奇特替代品,尽管其中许多都在内部使用数组.

例如,C#有一个名为List的集合,其功能与PHP数组非常相似.

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);
}
Run Code Online (Sandbox Code Playgroud)


Lea*_*dro 11

到2019年,您可以使用AppendPrepend使用LinQ中只有一行

using System.Linq;
Run Code Online (Sandbox Code Playgroud)

进而:

terms= terms.Append(21).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • 使用 List&lt;&gt; 通常是一个更好的主意,但如果真的想继续使用数组,这是最简单的方法! (3认同)

Thr*_*acx 10

正如其他人所描述的那样,使用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;
}
Run Code Online (Sandbox Code Playgroud)

我还可以发布一个Insert扩展方法的代码,该方法将目标索引作为输入,如果需要的话.它有点复杂,使用静态方法Array.Copy 1-2次.

  • 在性能上更好的做法是创建一个列表,将其填满,然后最后将此副本复制到阵列,因此您不必创建和复制该数组超过400次 (2认同)

Mar*_*ark 10

根据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;
    }
Run Code Online (Sandbox Code Playgroud)

这允许向数组添加多个项目,或者只是将数组作为参数传递以连接两个数组.


Mot*_*tti 8

你必须先分配数组:

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;
}
Run Code Online (Sandbox Code Playgroud)


JB *_*ing 5

int ArraySize = 400;

int[] terms = new int[ArraySize];


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

    terms[runs] = runs;

}
Run Code Online (Sandbox Code Playgroud)

这就是我编码的方式.


Mic*_*tum 5

您不能轻松地将元素添加到数组中。您可以按照Falling888 的概述将元素设置在给定位置,但我建议使用 aList<int>或 aCollection<int>代替,ToArray()如果需要将其转换为数组,则使用。


Ste*_*eve 5

如果您确实需要一个数组,以下可能是最简单的:

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();
Run Code Online (Sandbox Code Playgroud)