Remove element from a List at given index in C#
This post will discuss how to remove an element from a list at the given index in C#.
The List<T>.RemoveAt() method is the recommended way to remove an element at the specified index in a List<T>. The following code example demonstrates the usage of RemoveAt() method to remove an element at the index 2 in a List<T>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int>() { 1, 2, 3, 4 }; int indexToRemove = 2; list.RemoveAt(indexToRemove); Console.WriteLine(String.Join(", ", list)); // 1, 2, 4 } } |
The List<T>.RemoveAt() method throws a System.ArgumentOutOfRangeException if the specified index is out of range. The index parameter should be non-negative and less than the size of the list. We can easily handle it as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int>() { 1, 2 }; int indexToRemove = 2; if (indexToRemove >= 0 && indexToRemove < list.Count) { list.RemoveAt(indexToRemove); } Console.WriteLine(String.Join(", ", list)); // 1, 2 } } |
That’s all about removing elements from a list at the given index 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 :)