简体   繁体   中英

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.

" Property or indexer System.Collections.Generic.LinkedListNode<>.Next cannot be assigned to it is read only. "

        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. 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.

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.

You're trying to add items to other items, but you should be adding them to the LinkedList itself, which you're already doing:

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> . 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:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM