HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Removing n elements from array starting from index

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
startingelementsremovingarrayindexfrom

Problem

This method removes n elements starting from a given index, from an array of a given type. If n is positive it removes elements forwards, if it is negative it removes them backwards (e.g. for an array {1,2,3,4,5} Remove(2,2) results in {1,2,5}; Remove (2,-2) results in {1,4,5})

It there a better way to do it?

public static class ArrayExtensions
{
    public static T[] RemoveAt(this T[] array, int idx, int len)
    {
        T[] newArray;

        if (len > 0)
        {
            if (idx + len > array.Length)
                len = array.Length - idx;

            newArray = new T[array.Length - len];
            if (idx > 0)
                Array.Copy(array, 0, newArray, 0, idx);

            if (idx  0)
                Array.Copy(array, 0, newArray, 0, idx + len);

            if (idx < array.Length - 1)
                Array.Copy(array, idx, newArray, idx + len, array.Length - idx);
        }            

        return newArray;
    }
}

Solution

I believe that if the len < 0, it's better to adjust idx and len values. This will eliminate two branches of code.

Another suggestion is to use more readable variable names.

For instance, method arguments could be named startIndex and length respectively.

public static T[] RemoveAt(this T[] array, int startIndex, int length)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (length  array.Length)
        throw new ArgumentOutOfRangeException("length");

    T[] newArray = new T[array.Length - length];

    Array.Copy(array, 0, newArray, 0, startIndex);
    Array.Copy(array, startIndex + length, newArray, startIndex, array.Length - startIndex - length);

    return newArray;
}

Code Snippets

public static T[] RemoveAt<T>(this T[] array, int startIndex, int length)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (length < 0)
    {
        startIndex += 1 + length;
        length = -length;
    }

    if (startIndex < 0)
        throw new ArgumentOutOfRangeException("startIndex");
    if (startIndex + length > array.Length)
        throw new ArgumentOutOfRangeException("length");

    T[] newArray = new T[array.Length - length];

    Array.Copy(array, 0, newArray, 0, startIndex);
    Array.Copy(array, startIndex + length, newArray, startIndex, array.Length - startIndex - length);

    return newArray;
}

Context

StackExchange Code Review Q#132630, answer score: 12

Revisions (0)

No revisions yet.