[英]c# how to link 2 LinkedListNode?
I created a Linked list and a few nodes, I want to link those node, kept getting this error message. 我创建了一个Linked列表和几个节点,我想链接那些节点,不断收到此错误消息。
" Property or indexer System.Collections.Generic.LinkedListNode<>.Next cannot be assigned to it is read only. " “ 属性或索引器System.Collections.Generic.LinkedListNode <>。下一个无法分配给它是只读的。 ”
var link = new LinkedList<int>();
var node1 = new LinkedListNode<int>(1);
var node2 = new LinkedListNode<int>(2);
var node3 = new LinkedListNode<int>(3);
link.AddFirst(node1);
link.AddFirst(node2);
link.AddFirst(node3);
node1.Next = node2; ---> .next is read only
node2.Next = node3; ---> .next is read only
You need to use the AddAfter or AddBefore methods of the list. 您需要使用列表的AddAfter或AddBefore方法。 With these you can insert items directly before or after a given item.
使用这些,您可以直接在给定项目之前或之后插入项目。
Unfortunately the LinkedListNode<T>
class in .NET does not allow you to change the Next
and Previous
properties directly, since they don't have a set
accessor. 遗憾的是,.NET中的
LinkedListNode<T>
类不允许您直接更改Next
和Previous
属性,因为它们没有set
访问器。
If you want to change the ordering of the list, you'll also need to use the Remove method to remove the item from its previous position. 如果要更改列表的顺序,还需要使用“ 删除”方法从之前的位置删除项目。 I recommend the following form:
我推荐以下表格:
LinkedListItem<T> foo = /*fetch your item here*/
LinkedListItem<T> bar = /*the one to come right after foo,
as a result of running the code*/
list.Remove(foo);
list.AddBefore(bar, foo);
You could change that to insert after instead of inserting before. 您可以将其更改为插入而不是之前插入。
You don't have to link them. 您不必链接它们。 When you invoke the AddFirst method, it automatically links them to the first node which then becomes the second node.
当您调用AddFirst方法时,它会自动将它们链接到第一个节点,然后该节点成为第二个节点。
You're trying to add items to other items, but you should be adding them to the LinkedList
itself, which you're already doing: 您正在尝试将项目添加到其他项目,但您应该将它们添加到您已经在执行的
LinkedList
本身:
link.AddFirst(node1);
link.AddFirst(node2);
link.AddFirst(node3);
Are you trying to change their ordering? 你想改变他们的订单吗? It looks like that can only be done when adding them, based on the methods available on
LinkedList<T>
. 看起来只能在添加它们时才能完成,基于
LinkedList<T>
上的可用方法 。 So you would want to do something like this instead: 所以你想要做这样的事情:
link.AddFirst(node1);
link.AddAfter(node1, node2);
link.AddAfter(node2, node3);
Or, in your case, simply reversing the order of the calls to .AddFirst()
will produce the same results: 或者,在您的情况下,只需将调用顺序反转为
.AddFirst()
将产生相同的结果:
link.AddFirst(node3);
link.AddFirst(node2);
link.AddFirst(node1);
This would add node3
to the start of the list, then add node2
to the start of the list (pushing node3
to the second element), then add node1
to the start of the list (pushing node3
to the third element and node2
to the second element). 这会将
node3
添加到列表的开头,然后将node2
添加到列表的开头(将node3
推送到第二个元素),然后将node1
添加到列表的开头(将node3
到第三个元素,将node2
到第二个元素)元件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.