How to take elements from range with lambda expres

2019-05-05 00:16发布

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?

标签: c# linq lambda
6条回答
爷、活的狠高调
2楼-- · 2019-05-05 00:29

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);
查看更多
Luminary・发光体
3楼-- · 2019-05-05 00:29

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!

查看更多
女痞
4楼-- · 2019-05-05 00:38

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.

查看更多
该账号已被封号
5楼-- · 2019-05-05 00:44
List<int> list = new List<int>();
IEnumerable<int> interval = list.Skip(a).Take(b);
查看更多
叼着烟拽天下
6楼-- · 2019-05-05 00:44

You can use

.Skip(n1).Take(n2)
查看更多
Emotional °昔
7楼-- · 2019-05-05 00:52

Like this:

MyList.Skip(x).Take(y);
查看更多
登录 后发表回答