How to take elements from range with lambda expres

2019-05-05 00:15发布

问题:

How can I take elements by range with lambda and linq?

For example:

I have a table with 54 elements. I just want to take elements from possition 1-10, or 10-20 or 20-30 etc - generally by some numeric range.

How can I do this?

回答1:

List<int> list = new List<int>();
IEnumerable<int> interval = list.Skip(a).Take(b);


回答2:

You can use Enumerable.Skip and Enumerable.Take methods;

Bypasses a specified number of elements in a sequence and then returns the remaining elements.


Returns a specified number of contiguous elements from the start of a sequence.

List<int> yourlist = new List<int>(){1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
IEnumerable<int> newlist = yourlist.Skip(2).Take(3);

foreach(var i in newlist)
{
   Console.WriteLine(i);
}

Output will be;

3
4
5

Here is a DEMO.



回答3:

if what you want is pageing,

int pageIndex = 1;
int pageSize= 10

List<object> list = new List<object>();
IEnumerable<object> interval = list.Skip(pageIndex*pageSize).Take(pageSize);


回答4:

Like this:

MyList.Skip(x).Take(y);


回答5:

You can use

.Skip(n1).Take(n2)


回答6:

Use List<T>.GetRange(int index, int count);

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6 };
List<int> firstThreeNumbers = numbers.GetRange(0, 3);
List<int> lastThreeNumbers = numbers.GetRange(numbers.Count - 3, 3);

Don't Skip and Take, just GetRange!

Hope this helps!



标签: c# linq lambda