This post will discuss how to remove an element from a specific index in an array in C#.

1. Using Array.Resize method

The idea is to move elements one position to their left, starting from the specified index. Then, decrement the array’s size by one with the Array.Resize() method, as shown below:

Download  Run Code

2. Using Array.Copy Method

Alternatively, you can create a new array with the element at the specified index removed. The Array.Copy method copies a range of elements from an array to another array. It can be used as follows to copy all the elements of the original array to the new array, except the element at the specified index.

Download  Run Code

3. Using List<T>.RemoveAt Method

Another option is to convert the array into a List and invoke the List<T>RemoveAt() method on it to remove the element at the specified position. Then, transform the list back into a new array with the List.ToArray() method. This translates to the following code:

Download  Run Code

4. Using Enumerable.Where Method

The LINQ’s Enumerable.Where() method can be used to filter a sequence based on a predicate that involves the index of each element. The following code example demonstrates its usage to create an array instance with the specified element removed.

Download  Run Code

5. Using for loop

Finally, you can write a custom routine for removing an element from the specific index in the array. The following code example creates a new array of one less size and uses a for-loop to fill it with the corresponding values from the original array.

Download  Run Code

 
To be safe, consider placing the null-check and index-out-of-bound check for all the above solutions.

That’s all about removing an element from a specific index in an array in C#.