Remove first item from a List in C#
This post will discuss how to remove the first item from a list in C#.
1. Using List<T>.RemoveAt() Method
The RemoveAt() method remove element present at the specified position in the list. The idea is to pass the zero-index to the RemoveAt() method to remove the first element from it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4 }; numbers.RemoveAt(0); Console.WriteLine(String.Join(", ", numbers)); // 2, 3, 4 } } |
The RemoveAt() method throws an ArgumentOutOfRangeException if the specified index is out of range of valid indices. The following code example shows how to handle this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4 }; if (numbers.Count > 0) { numbers.RemoveAt(0); } Console.WriteLine(String.Join(", ", numbers)); // 2, 3, 4 } } |
2. Using List<T>.RemoveRange() Method
The List<T>.RemoveRange() method is used to remove a range of elements from a List<T>. It can be used as follows to remove only the first element from the list. The solution can be easily extended to remove a range of elements from the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4 }; numbers.RemoveRange(0, 1); Console.WriteLine(String.Join(", ", numbers)); // 2, 3, 4 } } |
Note that the RemoveRange() method throws an exception if the index and count do not denote a valid range of elements in the list. This can be handled by doing a range check before invoking the RemoveRange() method.
3. Using LinkedList<T>.RemoveFirst() Method
If you’re using a LinkedList<T>, you can use the RemoveFirst() method to remove the node at the start of the linked list in O(1) time. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Collections.Generic; public class Example { public static void Main() { // create a linked list 1 -> 2 -> 3 -> 4 LinkedList<int> list = new LinkedList<int>(); list.AddLast(1); list.AddLast(2); list.AddLast(3); list.AddLast(4); list.RemoveFirst(); Console.WriteLine(String.Join(", ", list)); // 2, 3, 4 } } |
That’s all about removing the first item from a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)