c#/.net xx 是否有双向链表的实现(可以向后迭代)?
我一直在寻找 C# 中双向链表的标准实现(以便我有一个可以向后迭代的链表),但找不到。我觉得如此简单的东西一定有一个我只是缺少的实现。
如果确实存在,那么它存在于哪个版本的 c#/.net 中?
一般来说,反向迭代似乎不适合在 C# 中完成。我的思维是否太停留在 c++/stl 模式上,或者这是 c# 中非常缺乏的东西?
我知道 LinkedList 但未能找到向后迭代它的方法,因此假设它是单链接的。
如果 LinkedList 是双向链接的,如何向后(有效)迭代它?
I've been searching for the standard implementation of a doubly linked list in c# (so that I have a linked list I can iterate over backwards) and cannot find one. I feel like something so simple must have an implementation that I'm just missing.
If it does exist, for which version of c#/.net does it exist?
Reverse iteration in general seems to be something not intended to be done in c#. Is my mind just stuck too much in c++/stl mode or is this something sorely lacking in c#?
I'm aware of LinkedList but in failing to find a way to iterate over it backwards had assumed it was singly linked.
If LinkedList is doubly linked how does one go about iterating over it backwards (Efficiently)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下代码将有效地反向迭代 LinkedList:
这里的关键是 LinkedList 仅包含对列表的第一个和最后一个 LinkedListNode 实例的引用。每个 LinkedListNode 实例都保存对列表中下一个和上一个项目的引用(或在列表的每一端为 null)以及一个 Value 属性。这意味着从第一个或最后一个 LinkedListNode 进行迭代很容易,但随机访问需要从列表中的第一个或最后一个进行迭代。
如果需要一路插入,请使用 LinkedList.AddBefore 或 AddAfter 插入新的 LinkedListNode。
The following code will efficiently iterate over a LinkedList in reverse:
The key here is that a LinkedList contains reference to only the First and Last LinkedListNode instances of the list. Each LinkedListNode instance holds a reference to the next and previous item in the list (or null at each end of the list) and also a Value property. This means iteration from the first or last LinkedListNode is easy, but random access requires iteration from the first or last in the list.
If you need to make an insertion along the way, use LinkedList.AddBefore or AddAfter to insert a new LinkedListNode.
除了此处给出的答案之外,您还可以为
LinkedList
编写一个扩展方法,以使其更容易重用:与以下方式一起使用:
As well as the answers given here, you can write an extension method to
LinkedList<T>
to make it slightly easier to reuse:Use with:
System.Collections.Generic.LinkedList() 怎么样
这是 MSDN 上的文档:
http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx
版本信息
.NET Framework:受以下版本支持:3.5、3.0、2.0
.NET Compact Framework:受支持版本:3.5、2.0
XNA 框架:支持版本:3.0、2.0、1.0
也就是说,我和其他人一样,在使用如此丰富的框架时通常最好使用更高的抽象。
How about System.Collections.Generic.LinkedList()
Here are the docs on MSDN:
http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx
Version Info
.NET Framework: Supported in: 3.5, 3.0, 2.0
.NET Compact Framework: Supported in: 3.5, 2.0
XNA Framework: Supported in: 3.0, 2.0, 1.0
That said, I am with the others that it is generally preferrable to use a higher abstraction when working with such a rich framework.
LinkedList 怎么样?
How about LinkedList?