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

47,523

Solution 1

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))

Solution 2

Just do:

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

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

Solution 3

Wouldn't it be...

foreach (var in list.Skip(1).AsEnumerable())
Share:
47,523
Marcel
Author by

Marcel

I am an experienced software developer for both technical and business software, mainly in C#/.NET. Most professional projects are web applications or web services in the telecommunications field, for large corporate customers. I work and live in Switzerland. In my spare time I build and hack hardware stuff and occasionally, I blog on https://qrys.ch about it.

Updated on July 09, 2022

Comments

  • Marcel
    Marcel almost 2 years

    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
    Marcel about 14 years
    Thanks man (banging my head against the keyboard for not seeing this obvious solution...)
  • Marcel
    Marcel about 14 years
    The AsEnumerable is not needed, as Mark's solution works perfectly.
  • Pat
    Pat about 14 years
    And if you wanted to take a certain number of values, you would simply do foreach (var item in list.Skip(1).Take(count))
  • Ajay Suwalka
    Ajay Suwalka over 7 years
    Skip(1) by default makes it Enumerable