4

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

balan
  • 179
  • 1
  • 5
  • 11
  • In general, I would not use Linq instead of functionality built into a type because it may be less performant. Linq works on IEnumerable meaning that the whole list must be traversed. GetRange may be more optimal. – Maciej Apr 02 '12 at 05:28
  • @Maciej I was under the impression that LINQ was transparently optimised when operating on `ICollection` and `IList`. Depending on the query, it does not necessarily mean that the entire list must be traversed. – Bradley Smith Apr 02 '12 at 05:53
  • @Bradley: Yes, in some cases it is optimized, but not always. See http://stackoverflow.com/questions/6245172/why-isnt-skip-in-linq-to-objects-optimized – Maciej Apr 02 '12 at 11:13

3 Answers3

10
var count = myList.Count;

myList.Skip(count-n)

Update:

removed redundant Take.

ZeNo
  • 1,648
  • 2
  • 15
  • 28
5

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

Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
  • 6
    You'd need an additional call to `Reverse` - `myList.Reverse().Take(n).Reverse()` - to return the elements in the same order as they are stored in the original list. – Lance U. Matthews Apr 02 '12 at 05:18
  • @BACON Good point, though order may not be important if the list contains only random numbers. – Bradley Smith Apr 02 '12 at 05:20
2

Use skip:

myList.Skip(index).ToArray()
McGarnagle
  • 101,349
  • 31
  • 229
  • 260