Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

My question is similar to Getting a sub-array from an existing array although a little different notion is very important in my case - I can't use memory copying.

Let's say I have array X of 10000 elements, I need array Y that would contains 9000 elements from X, starting from X's index 500.

But I don't want to copy part of X to new array Y, so I don't want to use Array.Copy, Array.Clone, System.Block.Copy, IEnumerables etc. I want Y to be reference to X - Y[0] would be in fact X[500], Y[1] corresponds to X[501], ..., Y[9000] is X[9500].

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

like image 940
xcoder37 Avatar asked Jun 01 '15 10:06

xcoder37


People also ask

How do I return a sub array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

How do you pass a sub array into a function?

You cannot pass an array to a function. When you try to, you actually pass the address of the first element of the array. If you need a subarray that starts at 5, you just pass the address of the fifth elements.


1 Answers

You could wrap it in 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];
             }    
         }
     }
}

This won't be an array, but a projection of one.

like image 101
Daniel A. White Avatar answered Oct 10 '22 20:10

Daniel A. White