tags:

views:

30

answers:

2

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: 

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);
Jon Skeet
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
@KJN: Will edit to make that clear.
Jon Skeet
+1  A: 

this may work for you:

list.Where((l, index) => index >= 1 && index <= 4  )
KJN
Note that iterating over that requires the *whole* sequence to be evaluated, even if logically you know you've finished.
Jon Skeet
Yes good point.
KJN