How do I get the n-th element in a LinkedList<T>?

pencilCake picture pencilCake · Apr 15, 2012 · Viewed 30.7k times · Source

How can I get the n-th element of a LinkedList instance? Is there a built-in way or I might need to introduce my own implementation? For example an extension method?

Thanks

Answer

Jon Skeet picture Jon Skeet · Apr 15, 2012

The ElementAt extension method will do it:

// This is 0-based of course
var value = linkedList.ElementAt(n);

Don't forget this is an O(n) operation because LinkedList<T> doesn't provide any more efficient way of accessing an item by index. If you need to do this regularly, it suggests that you shouldn't be using a linked list to start with.