Marcel
Marcel

Reputation: 15722

LINQ: How to skip one then take the rest of a sequence

i would like to iterate over the items of a List<T>, except the first, preserving the order. Is there an elegant way to do it with LINQ using a statement like:

foreach (var item in list.Skip(1).TakeTheRest()) {....

I played around with TakeWhile , but was not successful. Probably there is also another, simple way of doing it?

Upvotes: 61

Views: 63442

Answers (3)

ChrisF
ChrisF

Reputation: 137148

Just do:

foreach (var item in input.Skip(1))

There's some more info on Microsoft Learn.

Upvotes: 10

TomTom
TomTom

Reputation: 62093

Wouldn't it be...

foreach (var in list.Skip(1).AsEnumerable())

Upvotes: 5

Mark Byers
Mark Byers

Reputation: 838216

From the documentation for Skip:

Bypasses a specified number of elements in a sequence and then returns the remaining elements.

So you just need this:

foreach (var item in list.Skip(1))

Upvotes: 119

Related Questions