60

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?

Marcel
  • 15,039
  • 20
  • 92
  • 150

3 Answers3

117

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))
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Thanks man (banging my head against the keyboard for not seeing this obvious solution...) – Marcel Mar 12 '10 at 10:07
  • 3
    And if you wanted to take a certain number of values, you would simply do `foreach (var item in list.Skip(1).Take(count))` – Pat Mar 14 '10 at 00:05
10

Just do:

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

There's some more info on Microsoft Learn.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
5

Wouldn't it be...

foreach (var in list.Skip(1).AsEnumerable())
Marcel
  • 15,039
  • 20
  • 92
  • 150
TomTom
  • 61,059
  • 10
  • 88
  • 148