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?
How to make use of both Take and Skip operator together in LINQ C#? The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.
C# Linq Skip() MethodSkip elements and return the remaining elements using the Skip() method. The following is an array. int[] marks = { 80, 55, 79, 99 }; Now, let us skip 2 elements using Lambda Expressions, but this is done after arranging the elements in descending order.
Take<TSource>(IEnumerable<TSource>, Int32) Returns a specified number of contiguous elements from the start of a sequence. Take<TSource>(IEnumerable<TSource>, Range) Returns a specified range of contiguous elements from a sequence.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With