This post will discuss how to remove the last element from an array in C#.

We know that the size of arrays in C# is fixed. That means we can’t modify the size of an array once it is created, and there is no direct way to add or remove elements from it. If we need a dynamic array, the recommended approach is to use a List<T>. But if you insist on using arrays, create a new array to remove elements from it.

 
We can use any of the following methods to remove the last element from an array easily:

1. Using Enumerable.SkipLast() method

System.Linq.Enumerable.SkipLast() method returns a new collection having elements from source collection with specified elements from the end of the collection omitted. The following code example demonstrates how to use the SkipLast to skip the last element from the sequence.

Download  Run Code

2. Using Enumerable.Take() method

System.Linq.Enumerable.Take() method returns a specified number of contiguous elements from the start of a sequence. The following code example demonstrates how to use the Take to return all elements from the array except the last one.

Download  Run Code

3. Convert to List<T>

The idea is first to convert the array into a List<T>, then use its RemoveAt() method, which removes the element present at the specified position in the list. To remove the last element, we need to pass the index of the last element. This is demonstrated below:

Download  Run Code

4. Using Enumerable.Where() method

Enumerable.Where() method in System.Linq namespace filters a sequence of values based on a predicate. The following code example demonstrates how we can use the Where method to filter the last element from an array and return the remaining elements.

Download  Run Code

5. Using Array.Resize() method

We can resize the array to a smaller size to contain one less element using the Array.Resize() method. This is demonstrated below:

Download  Run Code

 
Note that the Resize method creates a new array with the specified size and does not modify the original array as fixed-size arrays.

6. Using Enumerable.Skip with Enumerable.Reverse

Reverse() method is used to invert the order of the elements in a sequence and Skip() method bypasses the specified number of items in a sequence and then returns the remaining elements.

The following code example demonstrates how the combination of Skip and Reverse can remove the last element from the array. This approach has low performance and is not recommended.

Download  Run Code

That’s all about removing the last element from an array in C#.

 
Related Post:

Remove the first element from an array in C#