How to get a submatrix from an existing array in C # without copying?

My question is similar to Getting a submatrix from an existing array , although in my case another concept is very important - I can not use memory copying.

Let's say I have an X array of 10,000 elements, I need an Y array that will contain 9,000 elements from X , starting at X index 500.

But I do not want to copy part X to a new array Y , so I do not want to use Array.Copy, Array.Clone, System.Block.Copy, IEnumerables, etc. I want Y to refer to X - Y[0] would actually be X[500] , Y[1] matches X[501] , ..., Y[9000] is X[9500] .

Thus, for example, changing the value of X[100] at the same time will change the value of Y[600] . How can I achieve this in C #?

+6
source share
3 answers

You can transfer it to another object with something like this:

 class View<T> { private T[] _array; private long _start; private long _length; public View(T[] array, long start, long length) { ... } public T this[long index] { get { if (/*do bounds check here*/) { return _array[_start + index]; } } } } 

It will not be an array, but a projection of one.

+7
source

You can use ArraySegment . Here is an example:

 String[] X = { "one", "two", "three", "four", "five"}; ArraySegment<String> arraySegment = new ArraySegment<String>(X, 1,3); // will contain {"two", "three", "four"} arraySegment.Array[arraySegment.Offset + 1] = "3"; // X will contain { "one", "two", "3", "four", "five"}; // and arraySegment.Array will contain {"two", "3", "four"} 
+2
source

Sadly, the ArraySegment<T> sealed, otherwise you could easily expand it using the appropriate array syntax, i.e. indexers, etc.

If I were you, I would go with ArraySegment<T> , and if it does not have proper requirements, such as ElementAt(n) for inefficiency, just do a better implementation. Example:

 public static class ArrayExtensions { // Getter using underlying array public static T GetValueAt<T>(this ArraySegment<T> array, int index) { // No safe checks here, would recommend them in production though return array.Array[array.Offset + index]; } // Setter using underlying array public static void SetValueAt<T>(this ArraySegment<T> array, int index, T value) { // maybe we should check that the calculated index is valid? Or just blow up? array.Array[array.Offset + index] = value; } } 
0
source

Source: https://habr.com/ru/post/988307/


All Articles