LINQ: How to skip one then take the rest of a sequence
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())
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, 2022Comments
-
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 about 14 yearsThanks man (banging my head against the keyboard for not seeing this obvious solution...)
-
Marcel about 14 yearsThe AsEnumerable is not needed, as Mark's solution works perfectly.
-
Pat about 14 yearsAnd 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 over 7 yearsSkip(1) by default makes it Enumerable