Home > Back-end >  Merge multiple array references/pointers in single array
Merge multiple array references/pointers in single array

Time:09-07

Is it possible to have an array which points to other arrays in C#?

double[] arr1 = new double[2]{1,2};
double[] arr2 = new double[2]{3,4};
double[] mergedArr = arr1   arr2; //of course not working like that, but how to do it right?

So when I change a value in arr1 the value in the mergedArray automatically changes?

CodePudding user response:

You could do something like this using Span<T> or Memory<T>

var arr = new double[]{1, 2, 3, 4};
var span1= arr.AsSpan(0, 2);
var span2= arr.AsSpan(2, 2);
span2[0] = 5;
// arr is now {1, 2, 5, 4}

Span<T> work kind of like a smart pointer that lets you refer to memory inside an array. But you have to start with the actual array, and create your spans from this, you cannot "merge" arrays, since they are different objects and will be placed in non-continous memory.

Note that Spans is very lightweight and cheap, but has some restrictions on how it can be used, Memory<T> is slightly less lightweight but removes some of the restrictions, I recommend reading the documentation to avoid any surprises.

CodePudding user response:

Points to other arrays -> this is not possible I think. Not sure. You can copy arrays to new array.

double[] arr1 = new double[2]{1,2};
double[] arr2 = new double[2]{3,4};
double[] arr3 = new double[arr1.Length  arr2.Length];
arr1.CopyTo(arr3, 0);
arr2.CopyTo(arr3 , arr1.Length);

CodePudding user response:

I think you are asking for a jagged array

double[] arr1 = new double[] {1, 2};
double[] arr2 = new double[] {3, 4};
double[][] jaggedArr = new double[][] { arr1, arr2};

which can be accessed via jaggedArr[0][1] => first array (0 index) and second element (1 index).

This creates an array of arrays { {1 ,2}, {3, 4} }

You can manually fill in the array of arrays which gives you more flexibility. For example

double[][] jaggedArr = new double[2][];
jaggedArr[0] = arr1;
jaggedArr[1] = arr2;

Unless you want to create an array from the values of the two arrays concatenated together (one after the other). Then you do

double[] concatArr = arr1.Concat(arr2).ToArray();

This creates a single array with values {1,2,3,4}.

CodePudding user response:

You should use IEnumerable, then you can use LINQ's Concat

IEnumerable<double> mergedArr = arr1.Concat(arr2);

This does not create a new object unless you call ToArray or ToList on it

  • Related