I have int list contains 5,6,7,8,5,4,3 i like retrieve the value from list using there 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
+4
A:
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);
Jon Skeet
2010-10-08 10:57:14
not that clear if he wanted to change that to select indexes 2 to 4 instead, say. You'd have to pass in list.Skip(2).Take(3) then.
KJN
2010-10-08 11:05:50
@KJN: Will edit to make that clear.
Jon Skeet
2010-10-08 11:08:41