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.
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.
This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with
Array.Resize<T>
: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.
In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.
Here's a small collection of helper methods I produced based on some of the existing answers. It utilizes both extensions and static methods with reference parameters for maximum idealness:
Performance wise, it is decent, but it could probably be improved.
Remove
relies onIndexOf
and a new array is created for each element you wish to remove by callingRemoveAt
.IndexOf
is the only extension method as it does not need to return the original array.New
accepts multiple elements of some type to produce a new array of said type. All other methods must accept the original array as a reference so there is no need to assign the result afterward as that happens internally already.I would've defined a
Merge
method for merging two arrays; however, that can already be accomplished withAdd
method by passing in an actual array versus multiple, individual elements. Therefore,Add
may be used in the following two ways to join two sets of elements:Or
I use this method for removing an element from an object array. In my situation, my arrays are small in length. So if you have large arrays you may need another solution.