-4

Possible Duplicate:
Using Linq to get the last N elements of a collection?

In C#, .NET, how can I get the last k elements of a List?

Community
  • 1
  • 1
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

3 Answers3

4
var klist = list.Skip(Math.Max(0,list.Count - k)).Take(k);
IvoTops
  • 3,463
  • 17
  • 18
3
MyList.GetRange(Mylist.Count - k, k);

http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

Dan
  • 45,079
  • 17
  • 88
  • 157
  • Not a fan of this answer, as it gives you a shallow copy of the elements. However, +1 as it's a good use of what's already there in the framework. – SPFiredrake Aug 21 '12 at 14:07
  • Could you not just fix that with .ToList()? – Dan Aug 21 '12 at 14:19
  • Not really, because GetRange returns a List already. GetRange creates a shallow copy of the elements in the range you specify, which might or might not be exactly what you're looking for. Reference types will just be the reference to the object itself, value types will be a copy of the object (but all references will be maintained). So a struct with any reference types will NOT be referentially equal, even though any reference properties might be. Just ambiguity that I prefer to stay away from. – SPFiredrake Aug 21 '12 at 14:38
  • OK, I thought that .ToList() would create a new list object not a reference. But otherwise it is a good thing to watch out for as as you say it could cause unexpected behaviour. – Dan Aug 21 '12 at 14:44
1

I assume you want something like:

myList.Reverse();
myList.Take(amount);
myList.Reverse();

Without more info, I can't give you a better answer.

Flater
  • 12,908
  • 4
  • 39
  • 62
  • This can be slow if the list is large. Anything with higher complexity than O(k) would be inefficient. Yours has O(n) where `n` is the totoal number of elements in the list. – Alex Aug 21 '12 at 14:05
  • 1
    Granted. I spent as much time thinking about the problem as the OP has. Well aware that this isn't really efficient. – Flater Aug 21 '12 at 14:07