How to remove the first element in an array?

C#ArraysLinq

C# Problem Overview


I have an array:

arr[0]="a"  
arr[1]="b"  
arr[2]="a"  

I want to remove only arr[0], and keep arr[1] and arr[2].
I was using:

arr= arr.Where(w => w != arr[0]).ToArray();  

Since arr[0] and arr[2] have the same value ("a"), the result I'm getting is only arr[1].

How can I return both arr[1] and arr[2], and only remove arr[0]?

C# Solutions


Solution 1 - C#

You can easily do that using Skip:

arr = arr.Skip(1).ToArray();  

This creates another array with new elements like in other answers. It's because you can't remove from or add elements to an array. Arrays have a fixed size.

Solution 2 - C#

You could try this:

arr = arr.ToList().RemoveAt(0).ToArray();

We make a list based on the array we already have, we remove the element in the 0 position and cast the result to an array.

or this:

arr = arr.Where((item, index)=>index!=0).ToArray();

where we use the overloaded version of Where, which takes as an argument also the item's index. Please have a look here.

Update

Another way, that is more elegant than the above, as D Stanley pointed out, is to use the Skip method:

arr = arr.Skip(1).ToArray(); 

Solution 3 - C#

How About:

if (arr.Length > 0)
{
    arr = arr.ToList().RemoveAt(0).ToArray();
}
return arr;

Solution 4 - C#

Use second overload of Enumerable.Where:-

arr = arr.Where((v,i) => i != 0).ToArray();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser990635View Question on Stackoverflow
Solution 1 - C#Selman GençView Answer on Stackoverflow
Solution 2 - C#ChristosView Answer on Stackoverflow
Solution 3 - C#User999999View Answer on Stackoverflow
Solution 4 - C#Rahul SinghView Answer on Stackoverflow