Reputation: 1494
How do you replace an element in a Linked list in C#? While in java either can use set or add method to replace a particular element in the list... I can´t find how do I replace it in C#.
Upvotes: 4
Views: 10817
Reputation: 112372
With LinkedList<T>
you work on LinkedListNode<T>
items. LinkedListNode<T>
has a Value
property that you can use get or set a particular item.
Unlike c#, Java does not have the concept of properties integrated in the language. In Java you create properties by adding hand-made set_Property and get_Property methods. The c# properties can be accessed like fields.
Java:
obj.set_MyProperty(123);
x = obj.get_MyProperty();
c#:
obj.MyProperty = 123;
x = obj.MyProperty;
Internally however, c# calls getter and setter methods as well. You would declare a property like this in c#:
private int _myProperty;
public int MyProperty {
get { return _myProperty; }
set { _myProperty = value; }
}
In this special case, when no other logic is involved you can use automatically implemented properties:
public int MyProperty { get; set; }
In your linked list, you would change the frst element of the list like this:
myLinkedList.Fist.Value = your new value;
Upvotes: 2
Reputation: 46937
Replace value 2 with 3:
LinkedList<int> ll;
ll.Find(2).Value = 3;
Upvotes: 15
Reputation: 134005
There is no Replace
method for a linked list node. To replace a node, you have to:
AddBefore
)You could also use AddAfter
. The result would be the same.
Upvotes: 8