Remove element of a regular array
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.
Solution 1:
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);
Solution 2:
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.