70

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]?

user990635
  • 3,689
  • 13
  • 42
  • 65

4 Answers4

211

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.

Mark Amery
  • 127,031
  • 74
  • 384
  • 431
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
21

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(); 
Theodor Zoulias
  • 24,585
  • 5
  • 40
  • 69
Christos
  • 52,021
  • 8
  • 71
  • 105
2

How About:

if (arr.Length > 0)
{
    arr = arr.ToList().RemoveAt(0).ToArray();
}
return arr;
User999999
  • 2,480
  • 7
  • 36
  • 62
1

Use second overload of Enumerable.Where:-

arr = arr.Where((v,i) => i != 0).ToArray();
Rahul Singh
  • 21,038
  • 6
  • 37
  • 55