78

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,979
  • 13
  • 45
  • 66

4 Answers4

233

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
  • 143,130
  • 81
  • 406
  • 459
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
23

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
  • 34,835
  • 7
  • 69
  • 104
Christos
  • 53,228
  • 8
  • 76
  • 108
2

Use second overload of Enumerable.Where:-

arr = arr.Where((v,i) => i != 0).ToArray();
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
2

How About:

if (arr.Length > 0)
{
    arr = arr.ToList().RemoveAt(0).ToArray();
}
return arr;
User999999
  • 2,500
  • 7
  • 37
  • 63