Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select bottom N from Generic List

Tags:

c#

linq

I have a generic list of integer and it contains random numbers. How would I select the last n elements from the list using LINQ?

I know can use myList.GetRange(index, count) to get the last n elements from the list. Is there a way to do it in LINQ?

THanks

regards, Balan

like image 955
balan Avatar asked Dec 04 '22 04:12

balan


2 Answers

var count = myList.Count;

myList.Skip(count-n)

Update:

removed redundant Take.

like image 159
ZeNo Avatar answered Dec 05 '22 17:12

ZeNo


You could use myList.Reverse().Take(n) to achieve what you want.

like image 36
Bradley Smith Avatar answered Dec 05 '22 17:12

Bradley Smith