Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 403
Marcel Avatar asked Mar 12 '10 09:03

Marcel


People also ask

How do you use take and skip in LINQ?

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.

How do you skip a method in C#?

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.

What is take in LINQ C#?

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.

Does LINQ select return new object?

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.


1 Answers

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)) 
like image 61
Mark Byers Avatar answered Sep 19 '22 16:09

Mark Byers