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#?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With