Get array tail

What is the easiest way to get the tail of an array in C # - i.e. all but the first element.

+6
c #
source share
5 answers
var myArray = GetSomeArray(); myArray = myArray.Skip(1).ToArray(); 

Note that I would avoid the maximum possible call to .ToArray () and stick with IEnumerable<T> instead of .Net.

+13
source share

Array.Copy :

 var array1 = new int[] { 1, 2, 3, 4, 5, 6 }; var array2 = new int[array1.Length - 1]; Array.Copy(array1, 1, array2, 0, array2.Length); // array2 now contains {2, 3, 4, 5, 6} 

Edit : Joel Coehorn's answer is better because it means you can not use arrays at all!

+6
source share

Lol call me old school, but hey its valid!

 for(int i = 1; i<array.length;i++) { array2[i-1]=array[i]; } 

: R

or you could give them if they were in a method, and you just need to call them, it just depends on what you want to do with the tail.

 for(int i = 1; i<array.length;i++) { yield return array[i]; } 
+1
source share

I prefer to answer codeka as it is a very simple and probably the most efficient way to do something. However, as you can see, this is not the easiest to implement when you need it.

I have something very similar as an extension method, so you can call SubArray and it will behave like a substring on a line.

Something like:

 public static T[] SubArray<T>(this T[] array, int startIndex, int length) { // various null, empty, out of range checks here T[] returnArray = new T[length]; Array.Copy(array, startIndex, returnArray, 0, length); return returnArray; } var array1 = new[] { 1, 2, 3, 4, 5 }; var arrays2 = array1.SubArray(2, 3); 

You can implement several other overloads, for example:

 public static T[] SubArray<T>(this T[] array, int startIndex) { // null check here return SubArray(array, startIndex, array.Length - startIndex); } 
0
source share
 using System.Linq; var array = new [] { 1, 2, 3, 4 }; var tail = array.Reverse ().Take (array.Length - 1).Reverse (); 
-one
source share

All Articles