Remove element of a regular array

leora picture leora · Jan 19, 2009 · Viewed 419.6k times · Source

I have an array of Foo objects. How do I remove the second element of the array?

I need something similar to RemoveAt() but for a regular array.

Answer

Andrew Kennan picture Andrew Kennan · Jan 19, 2009

If you don't want to use List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

You could try this extension method that I haven't actually tested:

public static T[] RemoveAt<T>(this T[] source, int index)
{
    T[] dest = new T[source.Length - 1];
    if( index > 0 )
        Array.Copy(source, 0, dest, 0, index);

    if( index < source.Length - 1 )
        Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

    return dest;
}

And use it like:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);