Remove first element from an array in C#
This post will discuss how to remove the first element from an array in C#.
We know that arrays in C# are fixed-size. That means we can’t modify the size of an array once it is created, and there is no direct way to add elements to it or remove any of its existing elements. If we need a dynamic array implementation, the recommended way is to use a List<T>. But if you insist on using arrays, you have to create a new array to remove any element from it.
We can use any of the following methods to easily remove the first element from an array in C#:
1. Using Enumerable.Skip() method
Enumerable.Skip() method can be used to skip the specified number of items in a sequence and then returns the remaining elements. The following code example demonstrates how to use the Skip to bypass the first element and return the remaining elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; array = array.Skip(1).ToArray(); Console.WriteLine(String.Join(",", array)); } } /* Output: 2,3,4,5 */ |
2. Convert to List<T>
The idea is first to convert the array into a List and then use its RemoveAt() method, removing the element present at the specified position in the list. To remove the first element, we need to pass an index of the first element. Finally, call the List.ToArray() method to return an array containing all the list elements. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; List<int> list = new List<int>(array); list.RemoveAt(0); array = list.ToArray(); Console.WriteLine(String.Join(",", list)); } } /* Output: 2,3,4,5 */ |
3. 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 first element from an array and return the remaining elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; array = array.Where((item, index) => index != 0).ToArray(); Console.WriteLine(String.Join(",", array)); } } /* Output: 2,3,4,5 */ |
That’s all about removing the first element from an array in C#.
Related Post:
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 :)