如何获得的第n个元素的链表&LT; T&GT;? [英] How do I get the n-th element in a LinkedList<T>?
本文介绍了如何获得的第n个元素的链表&LT; T&GT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能在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&LT; T&GT;
不提供通过索引访问的任何项目更有效的方式。如果你需要经常这样做,它表明,你不应该使用一个链表的开始。
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.
这篇关于如何获得的第n个元素的链表&LT; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文