Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip(m).take(n) from a List<T>?

Tags:

c#

linq

Given:

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

How do I implement the following code?

var list2 = list.skip(2).take(5);
like image 478
Mike108 Avatar asked Jan 21 '10 04:01

Mike108


People also ask

How to Skip elements from list in c#?

ToList(); list = list. Skip(0). Take(10);

How to use Take and Skip in 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 to use Skip and Take in linq?

In this article I am going to explain the Take and Skip operators in LINQ to SQL. The Take operator is used to return a given number of rows from a database table and the Skip operator skips over a specifed number of rows in a database table.

What does Take do in c#?

The Take() method extracts the first n elements (where n is a parameter to the method) from the beginning of the target sequence and returns a new sequence containing only the elements taken.


2 Answers

Your sample code will work as long as you include System.Linq in your using statements (and fix your method names .Skip(2) and .Take(5)).

The reason your code did not work out of the box is that .Skip and .Take are extension methods (as opposed to methods defined in the List class) found in the 'System.Linq' namespace.

like image 79
Esteban Araya Avatar answered Sep 20 '22 19:09

Esteban Araya


Have a look at the samples in the following link and its more easy to go with

LINQ 101 Sample

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

like image 45
Bala Avatar answered Sep 18 '22 19:09

Bala