简体   繁体   English

有没有办法向 C# 中的数组添加多个元素?

[英]Is there a way to add a number of elements to the array in C#?

I'm learning C# and I have created a code to add random numbers to a List using a for loop.我正在学习 C# 并且我创建了一个代码来使用for循环将随机数添加到List中。

class Program
{
    static void Main(string[] args)
    {
        Random numberGen = new Random();
        List<int> randomNum = new List<int>();
        for (int i = 0; i < 10; i++)
        {
            randomNum.Add(numberGen.Next(1, 100));
        }
        for (int i = 0; i < randomNum.Count; i++)
        {
            Console.WriteLine(randomNum[i]);
        }       
        Console.ReadKey();       
    }      
}

I want to know if there is a way to add random numbers to an array with a similar method?我想知道是否有一种方法可以使用类似的方法将随机数添加到数组中?

The size of an array is fixed at the time of creation, so you can't add to an array;数组的大小在创建时是固定的,所以不能添加到数组中; you can, however: create a new array that is bigger, copy the old data, and then append the new value(s) - Array.Resize does the first two steps - but: this is pretty expensive, which is why you usually use a List<T> or similar for this scenario.但是,您可以:创建一个更大的新数组,复制旧数据,然后 append 新值 - Array.Resize执行前两个步骤 - 但是:这非常昂贵,这就是您通常使用的原因用于此场景的List<T>或类似的。 A List<T> maintains an oversized array in the background, so that it only has to resize and copy the underlying array occasionally (essentially, it doubles the size every time it gets full, so you get something approximating O(Log2(N)) overhead due to growth). List<T>在后台维护一个超大数组,因此它只需要偶尔调整和复制底层数组(本质上,它每次变满时都会加倍大小,所以你得到的东西接近O(Log2(N))增长导致的开销)。

You could just assign to the relevant index directly, but note you'll have to initialize the array to the required size (as opposed to a List that can grow dynamically):您可以直接分配给相关索引,但请注意,您必须将数组初始化为所需的大小(而不是可以动态增长的List ):

int[] randomNum = new int[10];
for (int i = 0; i < randomNum.Length; i++)
{
    randomNum[i] = numberGen.Next(1, 100);
}

Use a List<T> , thats is the scenario it was precisely designed for.使用List<T> ,这就是它专门设计的场景。 Once you've finished adding elements to it, if you need an array then simply call ToArray() :完成向其中添加元素后,如果您需要一个数组,则只需调用ToArray()

var myList = new List<int>();
//add random number of random numbers
var myArray = myList.ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM