How to append arrays in c#

Viewed 38

I would like to get the output of this to be [1,2,3,4,...,200]. Any suggestions for how to go about this?

var Laser_data = 0;
var i = 0;
var j = 1;

int[] LaserData_200 = new int[200];

for (i = 0; i < LaserData_200.Length; i++)

{

 Laser_data += j;
 
 LaserData_200[i] = Laser_data;
 Console.WriteLine(" " + LaserData_200[i]);

}

Current output:

1

2

3

4

ect. 
2 Answers

Your array initialization and element assignment can be simplified massively. Your array is just the numbers 1 through 200 (inclusive). Enumerable.Range can generate that for you, then save it as an array.

int[] myArray = Enumerable.Range(1, 200).ToArray();

To print it all, string.Join it using a comma as a seperator.

Console.WriteLine($"[{string.Join(',', myArray)}]");
// [1,2,3,4,5,6,7,8,9,10,11,12,13, .... 200]

I see the title has nothing to do with the posted code.

So I am answering the question in the title.

Say you have two arrays a and b and you want to create a third array that combines the two arrays, then you write code like

int[] c = Enumerable.Concat(a, b).ToArray();

or you have and array a and you want to keep adding values to it in loop. When arrays are fixed size (a.IsFixedSize = true always) so you can do this efficiently.

The best solution is to use List<T> instead of an array

List<int> a = new List<int>() 
for(int i=0; i<200; i++)
{
    a.Add( i+1 );
}

and if you want an array in the end, you just do

int[] c= a.ToArray();
Related