我怎样才能在LinkedList实例的第n个元素?是否有一个内置的方法或我可能需要介绍一下我自己的实现?例如,一个扩展方法?
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?
感谢
在 的ElementAt
扩展方法做到这一点:
The ElementAt
extension method will do it:
// This is 0-based of course
var value = linkedList.ElementAt(n);
不要忘了这是一个O(n)的操作,因为的LinkedList< T>
不提供通过索引访问的任何项目更有效的方式。如果你需要经常这样做,它表明,你不应该使用一个链表的开始。
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.