views:

192

answers:

4

Hi All,

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?

+9  A: 

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
Thanks man (banging my head against the keyboard for not seeing this obvious solution...)
Marcel
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
+1  A: 

Just do:

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

There's some more info on the MSDN and a simple example here

ChrisF
Mark was first...
Marcel
@Marcel - indeed, by 31 seconds! I saw his answer after I hit the "add answer" button. I thought that I'd leave my answer as I included links to the MSDN so it's additional information. If Mark were to add the links to his answer then I'd probably delete mine (assuming I noticed of course ;))
ChrisF
ChrisF, what does the lock statement from the MSDN link have in common with the question?
Marcel
@marcel - it's a cut and past error. I thought I was copying the link to the skip msdn page. Thanks for pointing it out.
ChrisF
A: 

Wouldn't it be...

foreach (var in list.Skip(1).AsEnumerable()`)
TomTom
The AsEnumerable is not needed, as Mark's solution works perfectly.
Marcel
A: 

Nice example of Take and Skip in LINQ http://w3mentor.com/learn/asp-dot-net-c-sharp/c-asp-net-linq/example-of-take-and-skip-in-linq/