how to slice a doubles array in c#

I have a simple problem, but I am having a hard time getting the concept.

I have an array of doubles (doublesarray) and I want to slice the array so that I get the last "x" values.

x could be 2,5,7,12,etc

example:

doublesarray = {0,2,4,5,7,8,2,4,6};
doublesarray.slice(-4,-1);

output:
[8,2,4,6]


doublesarray.slice(-2,-1);
output:
[4,6]

Attempt:

I found some code online that slices, but it does not handle 2 negative inputs.

public static class Extensions
{
    /// <summary>
    /// Get the array slice between the two indexes.
    /// ... Inclusive for start index, exclusive for end index.
    /// </summary>
    public static T[] Slice<T>(this T[] source, int start, int end)
    {
        // Handles negative ends.
    if (end < 0)
    {
        end = source.Length + end;
    }
    int len = end - start;

    // Return new array.
    T[] res = new T[len];
    for (int i = 0; i < len; i++)
    {
        res[i] = source[i + start];
    }
    return res;
    }
}
Jon Skeet
people
quotationmark

Yes, the code you've shown already handles a negative end:

if (end < 0)
{
    end = source.Length + end;
}

So all you've got to do is the same thing for start:

if (start < 0)
{
    start = source.Length + start;
}

(Or use +=, i.e. start += source.Length.)

Note that this still won't handle large negative values - only values as far as -source.Length.

people

See more on this question at Stackoverflow