Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements but the first from an array

Tags:

c#

linq

Is there a one-line easy linq expression to just get everything from a simple array except the first element?

for (int i = 1; i <= contents.Length - 1; i++)
    Message += contents[i];

I just wanted to see if it was easier to condense.

like image 317
Ciel Avatar asked Apr 09 '10 21:04

Ciel


People also ask

How do you get all the elements of an array except first?

You can use array. slice(0,1) // First index is removed and array is returned. FIrst index is not removed, a copy is created without the first element.

How do you find an array without the first element?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do you slice the first element of an array?

Use the array. slice() method to remove the first element from an array, e.g. const withoutFirst = arr. slice(1); . The slice() method will return a shallow copy of the original array starting with the second element.


2 Answers

Yes, Enumerable.Skip does what you want:

contents.Skip(1)

However, the result is an IEnumerable<T>, if you want to get an array use:

contents.Skip(1).ToArray()
like image 96
LBushkin Avatar answered Oct 02 '22 01:10

LBushkin


The following would be equivalent to your for loop:

foreach (var item in contents.Skip(1))
    Message += item;
like image 32
Dan Stevens Avatar answered Oct 02 '22 01:10

Dan Stevens