C# 如何获取 LinkedList<T> 中的第 n 个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10164355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the n-th element in a LinkedList<T>?
提问by pencilCake
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?
如何获取 LinkedList 实例的第 n 个元素?是否有内置方法,或者我可能需要介绍自己的实现?例如扩展方法?
Thanks
谢谢
采纳答案by Jon Skeet
The ElementAtextension method will do it:
该ElementAt扩展方法会做到这一点:
// 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.
不要忘记这是一个 O(n) 操作,因为LinkedList<T>它没有提供通过索引访问项目的任何更有效的方法。如果您需要定期执行此操作,则建议您不应使用链表开始。
回答by MikeP
You can use the ElementAt() enumerable extension method. The reason LinkedList doesn't support random access natively is because it's a rather inefficient operation for the data structure. If you're going to be doing it often you should think about using a more appropriate data structure.
您可以使用 ElementAt() 可枚举扩展方法。LinkedList 本身不支持随机访问的原因是它对数据结构来说是一种相当低效的操作。如果您要经常这样做,您应该考虑使用更合适的数据结构。
回答by Jon
You can do it with LINQ as in list.ElementAt(n)or list.Skip(n - 1).First(), but if you find yourself making indexed access into a linked list you are probably doing something wrong (linked lists do not efficiently support this operation). Perhaps another data structure would be more appropriate?
您可以使用 LINQ 进行操作,如list.ElementAt(n)或list.Skip(n - 1).First(),但如果您发现自己对链表进行了索引访问,那么您可能做错了(链表不能有效地支持此操作)。也许另一种数据结构会更合适?
回答by Simon_Weaver
I needed to get the second element of my list (to update a value on the 1st item based on the 2nd)
我需要获取列表的第二个元素(根据第二个项目更新第一个项目的值)
Assuming you're taking the necessary steps to ensure you do have two items you can simply do this :
假设您正在采取必要的步骤来确保您确实有两个项目,您可以简单地执行以下操作:
list.First.Next.Value

