Best way to “push” into C# array

后端 未结 12 2621
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 14:25

Good day all

So I know that this is a fairly widely discussed issue, but I can\'t seem to find a definitive answer. I know that you can do what I am asking for using a L

12条回答
  •  臣服心动
    2021-02-13 14:46

    I surggest using the CopyTo method, so here is my two cent on a solution that is easy to explain and simple. The CopyTo method copies the array to another array at a given index. In this case myArray is copied to newArr starting at index 1 so index 0 in newArr can hold the new value.

    "Push" to array online demo

    var newValue = 1;
    var myArray = new int[5] { 2, 3, 4, 5, 6 };
    var newArr = new int[myArray.Length + 1];
    
    myArray.CopyTo(newArr, 1);
    newArr[0] = newValue;
        
    //debug
    for(var i = 0; i < newArr.Length; i++){
        Console.WriteLine(newArr[i].ToString());
    }
    
    //output
    1
    2
    3
    4
    5
    6
    

提交回复
热议问题