Home > front end >  is there a way to put two array into one array?
is there a way to put two array into one array?

Time:01-19

is there a way to put two arrays into one array so I can use the new array index? in c#

int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 6, 7, 8, 9, 0 };

int[[]] arr3 = {arr1,arr2};

CodePudding user response:

You can apply SelectMany() on arr3 to convert [[]] array of array to single flatten array.

var flattenArr = arr3.SelectMany(x => x).ToArray();

Or You can use List<T>.AddRange() to merge two lists into resultant one.

As you have input array, you need to convert arr1 and arr2 to lists first.

int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 6, 7, 8, 9, 0 };

var list1 = arr1.ToList();
var list2 = arr2.ToList();

var result = list1.AddRange(list2).ToArray();  //Here type of result is int[]

As @Klaus Gütter suggested in his comment you can use .Concat() method to concatenate two different arrays

int[] arr3 = arr1.Concat(arr2).ToArray()

CodePudding user response:

As others have mentioned you probably don't want to work with an array, since there are so many better collections. If, however, you insist, the barebones way of doing it is by using Array.Copy:

// Declare array of the needed length
var arr4 = new int[arr1.Length arr2.Length];
// Copy the first array into the new array
Array.Copy(arr1, arr4, arr1.Length);
// Copy the second array into the new array, at the end of the first
Array.Copy(arr2, 0, arr4, arr1.Length, arr2.Length);

CodePudding user response:

Maybe it is what you need

List<int[]> arr3 = new List<int[]>(){arr1,arr2};

Just use List

  •  Tags:  
  • Related