开发者

How to retrieve the values from list using indexes by linq query?

I have a list of int that contains 5,6,7,8,5,4,3. I like to retrieve the value from list using their index. For开发者_运维百科 example, I give start index as 1 and end index 4 I will get 6,7,8,5 in new list. How can I do this in Linq?


Use Skip and Take:

var results = list.Skip(1).Take(4);

EDIT: Note that it's not clear from your question exactly what limits you're using. If you're trying to be inclusive on both ends, using 0-based indexing, you want:

var results = list.Skip(startIndex).Take(endIndex - startIndex + 1);

Note that this won't let you get 0 results though - you may want to make endIndex exclusive so that if it equals startIndex, you get nothing. Then the code is:

var results = list.Skip(startIndex).Take(endIndex - startIndex);

Or an alternative approach is to use them the other way round. For example, the last snippet above is equivalent to:

var results = list.Take(endIndex).Skip(startIndex);


this may work for you:

list.Where((l, index) => index >= 1 && index <= 4  )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜