Zaid Khan
Zaid Khan

Reputation: 263

Append two or more array to a single master array

I am new to C# programming, I migrated from python. I want to append two or more array (exact number is not known , depends on db entry) into a single array like the list.append method in python does. Here the code example of what I want to do

int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] d;

I don't want to add all the arrays at a time. I need somewhat like this

// I know this not correct
d += a;
d += b;
d += c;

And this is the final result I want

d = {{1,2,3},{4,5,6},{7,8,9}};

it would be too easy for you guys but then I am just starting with c#.

Upvotes: 0

Views: 64

Answers (4)

Afnan Ahmad
Afnan Ahmad

Reputation: 2542

You can use Array.Copy. It copies a range of elements in one Array to another array. Reference

int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};

int[] combined = new int[a.Length + b.Length + c.Length];
Array.Copy(a, combined, a.Length);
Array.Copy(b, 0, combined, a.Length, b.Length);
Array.Copy(c, 0, combined, a.Length, b.Length, c.Length);

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Well, if you want a simple 1D array, try SelectMany:

  int[] a = { 1, 2, 3 };
  int[] b = { 4, 5, 6 };
  int[] c = { 7, 8, 9 };

  // d == {1, 2, 3, 4, 5, 6, 7, 8, 9}
  int[] d = new[] { a, b, c } // initial jagged array
    .SelectMany(item => item) // flattened
    .ToArray();               // materialized as a array

if you want a jagged array (array of arrays)

  // d == {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
  // notice the declaration - int[][] - array of arrays of int
  int[][] d = new[] { a, b, c };

In case you want to append arrays conditionally, not in one go, array is not a collection type to choose for d; List<int> or List<int[]> will serve better:

  // 1d array emulation
  List<int> d = new List<int>();
  ...
  d.AddRange(a);
  d.AddRange(b);
  d.AddRange(c); 

Or

  // jagged array emulation
  List<int[]> d = new List<int[]>();
  ...
  d.Add(a); //d.Add(a.ToArray()); if you want a copy of a  
  d.Add(b);
  d.Add(c);

Upvotes: 2

Tushar_G
Tushar_G

Reputation: 300

var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157116

It seems from your code that d is not a single-dimensional array, but it seems to be a jagged array (and array of arrays). If so, you can write this:

int[][] d = new int[][] { a, b, c };

If you instead want to concatenate all arrays to a new d, you can use:

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

Upvotes: 0

Related Questions