This post will discuss how to remove the last element from a List in C#.

1. Using List<T>.RemoveAt() Method

The RemoveAt() method removes the element present at the specified position in a list. To remove the last element, you can pass the index of it to the RemoveAt() method.

Download  Run Code

 
The above solution throws System.IndexOutOfRangeException for an empty list. You can easily handle this by checking the number of elements in the list.

Download  Run Code

 
Starting with C# 8.0, you can use the RemoveAt(^1) method instead of the RemoveAt(Count - 1) method.

Download  Run Code

2. Using LinkedList<T>.RemoveLast() Method

To remove an element from the end of the LinkedList<T>, consider using the RemoveLast() method. A linked list provides a more complete and consistent set of LIFO and FIFO operations. Here’s what the code would look like:

Download  Run Code

3. Using List<T>.RemoveRange() Method

The List<T>.RemoveRange() method is used to remove a range of elements from a List<T>. It takes the starting index of the range of elements to remove and the number of elements to remove. It can be used as follows to remove the last index. The solution can be easily extended to remove the last n elements from a list.

Download  Run Code

4. Using Enumerable.Take() Method

The following solution uses the Take() method to create a new list having all the elements of the original list except its last, and does not modify the original list.

Download  Run Code

That’s all about removing the last element from a List in C#.