如何获取 LinkedList<T> 中的第 n 个元素? [英] How do I get the n-th element in a LinkedList&lt;T&gt;?

查看:28
本文介绍了如何获取 LinkedList<T> 中的第 n 个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 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 没有提供任何更有效的按索引访问项目的方法.如果您需要定期执行此操作,则表明您不应使用链表开始.

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.

这篇关于如何获取 LinkedList<T> 中的第 n 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆